如何使Django视图仅在HTMX发出GET请求时可访问?

huangapple go评论47阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年2月14日 18:47:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75446740.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定