How can I check if the current request is from htmx
Asked Answered
C

3

5

I'm using Django, Is there a way to check if the current request is from HTMX

Curse answered 28/12, 2021 at 17:2 Comment(0)
A
11

You can check for HX-Request in the request headers, as mentioned in another answer. Or you can use the HTMX Django extension and simply check if request.htmx is True.

Anthropophagy answered 28/12, 2021 at 20:9 Comment(3)
That's it, thank you!Curse
@Curse I think it is unnecessary to use third party library to just check for htmx request when you can do it with django request itself no need of any other tool use HTTP_HX_REQUEST as i explained in my answer.Forespent
@Forespent you are correct, but the third party library offers other features like integrating HTMX responses with the Django debugger, which can be extremely helpful.Anthropophagy
F
5

Yes you can do this in Django by using HTTP_HX_REQUEST of request.META like this:

def myview(request):
   if request.META.get('HTTP_HX_REQUEST'):
      print("HTMX is available")
   else:
      print("HTMX is not available")
Forespent answered 28/12, 2021 at 18:21 Comment(0)
T
4

Regardless of the server-side solution you use, you can look for the HX-Request header. It will be set to true in all htmx requests. More information can be found here https://htmx.org/docs/#request-header

Ticknor answered 28/12, 2021 at 17:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.