`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
