$ show adamchainz/django-htmx
django-htmx is a mature, reusable Django library that integrates the htmx JavaScript library with Django. It provides a middleware that parses htmx headers and attaches an `HtmxDetails` object to each request (exposing properties like `boosted`, `current_url`, `target`), a set of HTTP response helpers for htmx interactions (e.g., `push_url`, `reswap`, `HttpResponseClientRedirect`), and template tags (for both Django and Jinja2) to include htmx scripts with version and extension selection. The library also bundles htmx versions 2 and 4 (beta) along with many extensions. It is a focused, well-tested package often used in production Django applications that need to leverage htmx for dynamic UI without writing JavaScript. The architecture is a standard reusable Django app with a clear separation of concerns: middleware for request processing, HTTP utilities for responses, and template tags for asset inclusion. Dependencies are minimal (Django 5.2+, asgiref). This is not a data research or analytics tool; it is purely a backend integration library.
The LLM identified 3 files worth highlighting for reuse:
Contains pure functions (push_url, replace_url, reswap, retarget, reselect, trigger_client_event) that modify Django HttpResponse objects by setting htmx-specific headers, and response classes (HttpResponseClientRedirect, HttpResponseClientRefresh, HttpResponseLocation, HttpResponseStopPolling) as subclasses of Django's HttpResponse. Also includes the ptag decorator for efficient polling with htmx 4. These are self-contained, well-documented utilities that can be reused in any Django project implementing htmx interactions, with no tight coupling beyond Django's base HTTP classes.
Implements HtmxMiddleware and HtmxDetails. The middleware processes every request, extracts htmx headers, and attaches an HtmxDetails instance to request.htmx. HtmxDetails uses Django's cached_property for lazy evaluation of headers like current_url, target, and triggering_event, and supports async views. This pattern of encapsulating request metadata into a typed object is reusable in any Django project that needs to parse custom headers, demonstrating clean separation of concerns and performance optimization.
Provides htmx_script() and django_htmx_script() functions that generate HTML script tags for htmx and its extensions. Supports specifying htmx version (2 or 4), minified/unminified builds, including multiple extensions, and CSP nonce injection. The functions return SafeString, making them safe for template rendering. This pattern of abstracting third-party script inclusion behind a Python API is reusable in any Django or Jinja2 project that wants to manage htmx versions programmatically without manual CDN links or copying scripts.