liveBook · Manning

Request.htmx

As explained in Django in Action

request.htmx is the django-htmx request attribute that exposes information about whether and how HTMX initiated a request.

`request.htmx` is added by django-htmx middleware. It represents HTMX request details and is truthy when HTMX initiated the request, letting one Django view choose the right response. section 12.4

Use it when a URL must serve both a normal page load and an HTMX update. Build the same context either way, then return a partial for HTMX or the full template for an ordinary request. section 12.4

Search results without a second view

A musician search view checks `if request.htmx`: HTMX keystroke and infinite-scroll requests receive only the results template; direct visits receive the complete search page. 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)

The conditional sits after query preparation, so both request modes share search logic and differ only in the rendered template. section 12.4

How Django in Action covers it

How deep it goes
Demonstrates Boolean detection in complete search and pagination view flows, while noting broader request details without using them.
Examples
Uses musician search-as-you-type, result partials, pagination, and revealed-trigger infinite scroll.
What it assumes
Assumes a Django view and templates, then shows installing django-htmx and enabling its middleware.
What you can do after
Apply it via django-htmx to return HTMX partials while preserving full-page responses for direct visits.
How it connects
Connects HTMX, django-htmx middleware, Django views, templates, pagination, and infinite scroll.

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.