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: true header; 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
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.