英文:
How to make Django view accessible only when a GET request is issued by HTMX?
问题
我正在尝试学习如何在Django中使用HTMX。
我有一个简单的HTMX按钮,当您点击它时,页面上会显示一些经过筛选的结果。
问题是,当用户转到用于通过GET请求显示内容的指定URL时,他们可以看到页面的内容。
他们应该只能在按下HTMX按钮时才能看到这个内容,而不是通过导航到HTMX获取内容以显示内容的URL。
有没有办法来处理这个问题?
英文:
I am trying to learn HTMX for using it with Django.
I have a simple HTMX button that when you click you get some filtered results on the page.
The problem is that when users go to the specified URL provided for the purpose of showing content through the GET request, they can see the content of the page.
They should only be able to see this content when they press the HTMX button though, not by navigating to the URL HTMX gets in order to show the content.
Is there any way on how to handle this?
答案1
得分: 2
你可以通过检查一个名为HX-Request
的特定标头来实现这一点,它始终由HTMX设置为true
。因此,如果用户访问一个仅限HTMX的端点,并且请求标头没有HX-Request
键,你可以响应一个错误、404,或将用户转发到不同的端点。
英文:
You can achieve this by checking for a specific header called HX-Request
that is always set to true
by HTMX. So if a user visits a HTMX only endpoint and the request header does not have the HX-Request
key you can response with an error, 404, or forward the user to a different endpoint.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论