Extensions for using Django with htmx.
Python 3.5 to 3.9 supported.
Django 2.2 to 3.1 supported.
Are your tests slow? Check out my book Speed Up Your Django Tests which covers loads of best practices so you can write faster, more accurate tests.
Install with pip:
python -m pip install django-htmx
Add the middleware:
MIDDLEWARE = [ ..., "django_htmx.HtmxMiddleware", ..., ]
The middleware does a few things:
- It attaches
request.htmx
, an instance ofdjango_htmx.HtmxDetails
(see below). - It modifies
request.method
based upon theX-HTTP-Method-Override
header. htmx sends this header to set what the method “really is” since the JavaScriptXMLHttpRequest
API only allows sendingGET
andPOST
requests.
This class provides shortcuts for reading the htmx-specific request headers.
True
if the request was made with htmx, otherwise False
.
This is based on the presence of the HX-Request
header.
This allows you to switch behaviour for requests made with htmx like so:
def my_view(request):
if request.htmx:
template_name = "partial.html"
else:
template_name = "complete.html"
return render(template_name, ...)
The id
of the active element if it exists, or None
.
Based on the HX-Active-Element
header.
The name
of the active element if it exists, or None
.
Based on the HX-Active-Element-Name
header.
The value
of the active element if it exists, or None
.
Based on the HX-Active-Element-Value
header.
The current URL of the browser, or None
for non-htmx requests.
Based on the HX-Current-URL
header.
The id
of the original event target element, or None
.
Based on the HX-Event-Target
header.
The user response to hx-prompt if it was used, or None
.
The id
of the target element if it exists, or None
.
Based on the HX-Target
header.
The id
of the triggered element if it exists, or None
.
Based on the HX-Trigger
header.
The name
of the triggered element if it exists, or None
.
Based on the HX-Trigger-Name
header.