A simple middleware for Django applications to detect HTMX requests, adding an is_htmx attribute to the request object for convenient usage in views. It also includes a fix for handling redirects and works seamlessly with the django-template-partials.
- HTMX Detection: Automatically detects if a request originates from HTMX and adds an
is_htmxattribute to the request object. - Redirect Fix: Includes a modification to correctly handle redirects during HTMX requests.
- Integration: Works with
django-template-partialsfor partial rendering support.
Add the middleware to your Django settings.py file under the MIDDLEWARE configuration:
MIDDLEWARE = [
...,
'yourapp.middlewares.HtmxMiddleware',
...,
]Replace 'yourapp.middlewares.HtmxMiddleware' with the actual path to your HTMX middleware module.
Once configured, the middleware will automatically add an is_htmx property to the request object. You can use this attribute in your views to determine if a request was made via HTMX:
from django.shortcuts import render
def my_view(request):
if request.is_htmx:
# Handle the HTMX request
return render(request, 'index.html#customform')
else:
# Handle a normal request
return render(request, 'index.html')The middleware includes a redirect fix to ensure smooth navigation when using redirects in HTMX requests. This is automatically handled, so no additional setup is required.
For more information on HTMX, visit htmx.org.