Search code examples
djangohtmx

How to make Django view accessible only when a GET request is issued by HTMX?


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?


Solution

  • 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.