Skip to content

Instantly share code, notes, and snippets.

@rayyildiz
Last active February 4, 2025 10:12
Show Gist options
  • Select an option

  • Save rayyildiz/da5add460e58348120d6388cfa649815 to your computer and use it in GitHub Desktop.

Select an option

Save rayyildiz/da5add460e58348120d6388cfa649815 to your computer and use it in GitHub Desktop.
Middleware for handling HTMX-specific request and response processing.

Django HTMX Middleware

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.

Features

  • HTMX Detection: Automatically detects if a request originates from HTMX and adds an is_htmx attribute to the request object.
  • Redirect Fix: Includes a modification to correctly handle redirects during HTMX requests.
  • Integration: Works with django-template-partials for partial rendering support.

Configuration

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.

Usage

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')

Redirect Fix

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.

{% partialdef customform inline %}
<form ...
{% endpartialdef customform %}
class HtmxMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
request.is_htmx = request.headers.get("hx-request", "false") == "true"
response = self.get_response(request)
# fix for 3xx status codes, see more https://htmx.org/headers/hx-redirect/
if request.is_htmx and (redirect_location := response.headers.get("Location")):
response.headers["HX-Redirect"] = redirect_location
response.status_code = 200
return response
# add to middleware
MIDDLEWARE = [
# add middleware
"yourapp.middlewares.HtmxMiddleware",
# ...
]
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')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment