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:
- Install it with python -m pip install django-htmx. section 12.4
- Add django_htmx to INSTALLED_APPS. section 12.4
- Add django_htmx.middleware.HtmxMiddleware to MIDDLEWARE. section 12.4
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
