liveBook · Manning

Django-htmx

As explained in Django in Action

django-htmx is a Django library that integrates HTMX request information into Django request processing, including through middleware.

django-htmx lets Django views recognize HTMX requests without manually inspecting the HX-Request header. Its middleware adds request.htmx, which is truthy for an HTMX call, so one view can return a full page for normal navigation or a partial template for an HTMX update. section 12.4

Set it up in three small steps:

Render search results appropriately

A musician search view builds its context once, then checks request.htmx. HTMX requests render only partials/musician_results.html; ordinary requests render search_musicians.html, which includes that partial. This supports search-as-you-type while preserving a normal page response. section 12.4

Listing 12.9 An HTMX-capable search view
# RiffMates/bands/views.py
...
def search_musicians(request):
    search_text = request.GET.get("search_text", "")
    search_text = urllib.parse.unquote(search_text)
    search_text = search_text.strip()

    musicians = []

    if search_text:
        parts = search_text.split()

        q = Q(first_name__istartswith=parts[0]) | \
            Q(last_name__istartswith=parts[0])
        for part in parts[1:]:
            q |= Q(first_name__istartswith=part) | \
                Q(last_name__istartswith=part)

        musicians = Musician.objects.filter(q)

    data = {
        "search_text": search_text,
        "musicians": musicians,
    }

    if request.htmx: #1
        return render(request, "partials/musician_results.html", data)

    return render(request, "search_musicians.html", data)

Compare the shared search logic with the short request.htmx branch that chooses the partial or full template. section 12.4

How Django in Action covers it

How deep it goes
Explains installation, middleware configuration, and Boolean request.htmx branching, while only noting additional library features.
Examples
Demonstrates a musician search page that returns a results partial for search-as-you-type and infinite scrolling.
What it assumes
Assumes a Django project with settings, views, and templates; introduces the HTMX request distinction directly.
What you can do after
Apply it via django-htmx middleware to make a Django view distinguish HTMX calls and render a partial.
How it connects
Connects HTMX requests with Django middleware, views, templates, partial templates, redirects, and response classes.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Django in Action. The section links point to the parts of the book it draws on.