Handle HTMX Requests in Views
Serve partial HTML when HX-Request header is present.
# models.py
from django.db import models
class Todo(models.Model):
title = models.CharField(max_length=120)
is_done = models.BooleanField(default=False)
# views.py
from django.shortcuts import render
from .models import Todo
def todo_list(request):
template = "todos/partial_list.html" if request.headers.get("HX-Request") else "todos/list.html"
return render(request, template, {"todos": Todo.objects.all()})
# templates/todos/partial_list.html (HTMX partial)
<ul>
{% for todo in todos %}
<li>{{ todo.title }}{% if todo.is_done %} ✓{% endif %}</li>
{% endfor %}
</ul>
# templates/todos/list.html (Full page)
{% extends "base.html" %}
{% block content %}
<div hx-get="/todos/" hx-trigger="load" hx-swap="innerHTML">
{% include "todos/partial_list.html" %}
</div>
{% endblock %}
Explanation:
-
HTMX sends
HX-Request: trueheader; switch templates accordingly. - Return small partials to update page fragments without full reload.
- Category Views (FBV & CBV)
- Total Views 1270
- Last Modified 30 December, 2025
- Tags #htmx #partials #views #ajax
Previous snippet
Async Methods in Class-Based Views
Next snippet