Django templates, htmx or an API: choosing the front end

TL;DR

Difficulty: Intermediate

Count your clients, then count the copies of each business rule.

  • One client, a browser: Django templates and forms, with htmx for the parts that move. One codebase, one copy of each rule.
  • A second client, such as a mobile app: add an API with Django REST Framework or Django Ninja for that client, calling the same Python functions.
  • A JavaScript front end earns its cost for offline products, spreadsheet or map style screens and front end led teams. It costs two codebases, extra copies of your rules, cross origin authentication and work for search engines.
  • The worked example: a live workshop board in about 140 lines of Django and htmx, polling first, server sent events when the numbers call for them.

Every Django project reaches the same fork: let Django render the HTML, or turn it into an API behind a JavaScript front end. The loud answers on both sides are not about your project. Here is a rule that is, worked through on a bicycle repair chain's live workshop board, with code for Django 5.0, htmx 1.9 and Django REST Framework.

The question behind this chapter

You have a Django project. The models are in place, the admin already gives the managers a back office, and now somebody has to decide how the screens are built. Should Django render the HTML itself, with templates and a little htmx for the parts that move? Or should Django become an API, a set of URLs that answer in JSON, behind a JavaScript front end written in React, Vue or Svelte?

The question arrives with a lot of noise attached. One camp says a modern product needs a single page application (SPA). The other says SPAs were a detour and HTML is back. Neither camp is talking about your project.

This chapter answers it for a real kind of application, with code you can run on Django 5.0 and htmx 1.9. I keep using the invented example of this series: Freewheel Cycles, a chain of six bicycle repair workshops in Limerick (freewheelcycles.example), founded by Niamh, with two developers, Aisling and Cian. In the decision chapter they chose Rails for the product, but they built a two week spike of the core in both frameworks first. What follows is the Django version of the spike, so you can lay it next to the Hotwire chapter of the Rails series and compare like for like.

If you have not read how a Django project is structured, start there. This chapter assumes you know what a view, a URL pattern and a template are.

My rule: count the clients, then count the copies of each rule

Most comparisons of templates, htmx and APIs list features. I find a different pair of questions settles it faster.

How many clients does this application have today? A client is any piece of software that talks to your server: a browser showing your pages, a mobile app, a partner's system, a script. A browser that renders HTML your server sends is one client. A React application in that browser is also one client, but it needs data instead of HTML. A mobile app is a second client.

How many copies of each business rule will you have to keep? A rule like "a booking must be in the future" or "a job card can only move from waiting to in repair" has to be enforced somewhere. Every extra place it lives is a place it can drift. Two copies that disagree are a bug that no single test catches.

My rule of thumb, and it is mine rather than anything in the Django docs: build the API when you get the second client, not for the first one. For one client, a browser, server rendered HTML keeps one codebase and one copy of each rule. The day a second client arrives, you add an API for that client, and you keep the rules in the models and in plain Python functions that both the HTML views and the API call. That way the second client costs you one extra layer, not a second copy of the business.

The htmx authors make a related point from the other side: they argue for deciding feature by feature, and note it is typically easier to embed SPA components within a hypermedia application than the reverse1. Counting clients and copies is how I turn that into a decision you can defend in a meeting.

Example: the copies of "a booking must be in the future" at Freewheel Cycles

Freewheel takes about 1,150 repair bookings a week. A customer must not book a slot that has already passed. Count where that rule lives in each approach.

  • Templates and forms. The rule lives in the Booking model's clean() method. A Django ModelForm calls the model's validation when the form is validated2, so the booking form and the admin both enforce it. One copy.
  • Templates and htmx. Exactly the same. htmx only changes how the form is sent and how the answer is shown. One copy.
  • API behind a React front end. The model still has it, for the admin. Django REST Framework's ModelSerializer deliberately does not call the model's clean()3, so the API needs its own check in the serializer. And the React form will want to show the error before the customer presses the button, so it gets a third copy in JavaScript. Three copies, in two languages.

Three copies are manageable for one rule. Freewheel will have dozens: slot lengths, opening hours per workshop, which statuses a card may move to, VAT at 23% on invoices. Multiply, and you see why the front end decision is really a decision about how many places your business logic lives.

Option one: classic templates and forms

This is the approach Django was designed around, and it is still the one with the fewest moving parts.

The template language. A Django template is a text file, usually HTML, with variables in double curly braces ({{ booking.starts_at }}) and tags between {% and %} ({% for card in cards %})4. Variables are escaped by default: if a customer types <script> into the notes field, the page shows the text instead of running it. That one default closes the most common cross site scripting hole.

Inheritance. A base template defines the frame of every page (the head, the navigation, the footer) and leaves named blocks open. Each page template says {% extends "base.html" %} and fills the blocks it needs4. {% include %} pulls a smaller template into a bigger one. You will use that heavily with htmx.

Forms and ModelForms. A Django form class describes fields, converts what the browser sends into Python values and collects error messages. A ModelForm builds the form from a model, so the fields, their types and their validation come from one place2.

Cross site request forgery (CSRF) protection. A CSRF attack tricks a logged in user's browser into submitting a form to your site from somewhere else. Django's middleware rejects any unsafe request (POST, PUT, DELETE) that does not carry a secret token. In a template you add {% csrf_token %} inside each form5.

The messages framework. After a successful POST, a well behaved view redirects, so that pressing refresh does not book the repair twice. The messages framework carries a one time note ("Your booking is confirmed") across that redirect6.

Example: the Freewheel booking form, done well

The Booking model holds the rule, once:

# bookings/models.py
from django.core.exceptions import ValidationError
from django.db import models
from django.utils import timezone


class Booking(models.Model):
    workshop = models.ForeignKey("workshops.Workshop", on_delete=models.PROTECT)
    customer = models.ForeignKey("customers.Customer", on_delete=models.PROTECT)
    starts_at = models.DateTimeField("Date and time")
    problem = models.TextField(
        "What needs fixing?",
        help_text="For example: gears slipping, rear brake rubbing.",
    )

    def clean(self):
        # The one copy of the rule. ModelForm and the admin both run it.
        if self.starts_at and self.starts_at < timezone.now():
            raise ValidationError({"starts_at": "Please choose a time that has not passed yet."})

The form is three lines, because the model already knows everything:

# bookings/forms.py
from django import forms

from .models import Booking


class BookingForm(forms.ModelForm):
    class Meta:
        model = Booking
        fields = ["workshop", "starts_at", "problem"]
        widgets = {"starts_at": forms.DateTimeInput(attrs={"type": "datetime-local"})}

The view follows the pattern every Django developer knows: show the form, validate, save, redirect, say thank you.

# bookings/views.py
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, render

from .forms import BookingForm


@login_required
def new_booking(request):
    form = BookingForm(request.POST or None)
    if request.method == "POST" and form.is_valid():
        booking = form.save(commit=False)
        booking.customer = request.user.customer  # set on the server, never trusted from the form
        booking.save()
        messages.success(request, "Your booking is confirmed. We will email you the details.")
        return redirect("bookings:mine")
    # On GET, or when validation failed, render the form again with its errors.
    return render(request, "bookings/new.html", {"form": form})

And the template uses inheritance plus Django 5.0's field group rendering:

{% extends "base.html" %}
{% block content %}
  <h1>Book a repair</h1>
  <form method="post">
    {% csrf_token %}
    {{ form.non_field_errors }}
    {{ form.workshop.as_field_group }}
    {{ form.starts_at.as_field_group }}
    {{ form.problem.as_field_group }}
    <button type="submit">Book the repair</button>
  </form>
{% endblock %}

as_field_group is new in Django 5.0. It renders the label, the widget, the help text and the errors of one field from a single template, which you can override once for the whole project7. Before 5.0 you wrote those four pieces by hand for every field, and every developer wrote them a little differently.

That is a complete, secure booking form. No JavaScript, no build step, no second codebase.

Forms that everyone can use

A form is where a web application most often fails people who use a screen reader, a keyboard or a magnifier. Freewheel's customers include people with low vision and people booking from a phone with one hand while holding a bike with the other.

Django 5.0 made two concrete improvements here. Form fields now carry aria-describedby, which tells a screen reader which help text belongs to which field, and invalid fields now carry aria-invalid="true"7. The release notes say nothing about linking error messages to their field in the same way, so check the rendered HTML yourself and add it to your project's field template if your screen reader does not announce the error with the field.

The law matters too. Ireland is in the EU, so the European Accessibility Act applies here. For what it asks of a business, see my article on accessibility law for online businesses.

Example: what the booking form tells a screen reader

Suppose a customer picks yesterday by mistake. Here is what the server sends back for that field, roughly, with Django 5.0's default templates:

<div>
  <label for="id_starts_at">Date and time:</label>
  <ul class="errorlist"><li>Please choose a time that has not passed yet.</li></ul>
  <input type="datetime-local" name="starts_at" id="id_starts_at" aria-invalid="true" required>
</div>

Walk through it as a screen reader user would. The label is joined to the input by for and id, so the field is announced as "Date and time". aria-invalid="true" adds "invalid entry". The error text sits right above the field, so a sighted user sees it at once. To make the screen reader read it out when the field gets focus, give the error list an id in your field template and add that id to the input's aria-describedby. That is a small, one time change to one template, and every form in the project gets it.

Option two: templates plus htmx

htmx is a small JavaScript library (about 14 kB minified and compressed, by its own home page8) that lets any HTML element send an HTTP request and swap the HTML that comes back into the page9. You write no JavaScript for it. You write attributes:

  • hx-get, hx-post: which URL to call, with which method.
  • hx-target: which element on the page receives the answer.
  • hx-swap: how to put it there, for example outerHTML to replace the target element itself.
  • hx-trigger: what starts the request: a click, a change, or a timer such as every 10s.

Every request htmx sends carries a header, HX-Request: true9. Your Django view reads it and decides: a normal browser request gets the full page, an htmx request gets only the fragment that changed. The current release is 1.9.12, from 17 April 202410.

Two helper packages are worth naming, fairly, because many teams use them:

  • django-htmx by Adam Johnson (version 1.17.3 at the time of writing) adds a middleware that puts request.htmx on every request, so you can write if request.htmx: instead of reading the header yourself, plus helpers for htmx's response headers11.
  • django-template-partials by Carlton Gibson lets you define named fragments inside one template and render just that fragment from a view12. In this chapter I use plain {% include %} files instead, so the code runs on Django alone, but partials are a tidy alternative once a template grows several fragments.

What about CSRF? htmx sends a normal POST, so Django's protection applies. If the request comes from a real <form> with {% csrf_token %} inside, the token travels with the form fields. For buttons outside a form, the django htmx docs recommend putting the token into a header for the whole page with hx-headers on the <body> tag13.

Example: one view that answers both kinds of request

The smallest useful htmx view at Freewheel: the list of today's bookings for one workshop, which the manager can filter without reloading the page.

# bookings/views.py
from django.shortcuts import render
from django.utils import timezone

from .models import Booking


def todays_bookings(request, workshop_id):
    bookings = Booking.objects.filter(
        workshop_id=workshop_id, starts_at__date=timezone.localdate()
    ).order_by("starts_at")
    # A full page for a normal visit, only the table for an htmx request.
    template = "bookings/_table.html" if request.htmx else "bookings/today.html"
    return render(request, template, {"bookings": bookings})

today.html extends the base template and contains {% include "bookings/_table.html" %}. So the table is written once, and the same URL serves a whole page to a bookmark, a refresh or a browser with JavaScript switched off, and a fragment to htmx. That property, a URL that still works without JavaScript, is called progressive enhancement, and htmx's docs describe it as degrading gracefully9.

The worked example: Freewheel's live workshop board

Now the real test. The workshop board is the screen that made Freewheel consider a JavaScript front end in the first place. Each workshop has a screen on the wall, and every mechanic has the board on a phone. Job cards sit in columns: waiting, in repair, ready. A mechanic presses a button and the card moves. Everyone else sees it move without touching anything.

I build it in five steps, then deal with "without touching anything" in the next section.

Step 1: the model holds the rule

# repairs/models.py
from django.db import models


class JobCard(models.Model):
    class Status(models.TextChoices):
        WAITING = "waiting", "Waiting"
        IN_REPAIR = "in_repair", "In repair"
        READY = "ready", "Ready"
        COLLECTED = "collected", "Collected"

    # The one copy of the workflow: where each status may go next.
    NEXT = {
        Status.WAITING: Status.IN_REPAIR,
        Status.IN_REPAIR: Status.READY,
        Status.READY: Status.COLLECTED,
    }
    # What the button says for each status.
    ACTION = {
        Status.WAITING: "Start repair",
        Status.IN_REPAIR: "Mark ready",
        Status.READY: "Handed over",
    }

    booking = models.OneToOneField("bookings.Booking", on_delete=models.PROTECT, related_name="job_card")
    workshop = models.ForeignKey("workshops.Workshop", on_delete=models.PROTECT, related_name="job_cards")
    mechanic = models.ForeignKey("workshops.Mechanic", null=True, blank=True, on_delete=models.SET_NULL)
    status = models.CharField(max_length=20, choices=Status, default=Status.WAITING)
    updated_at = models.DateTimeField(auto_now=True)

    @property
    def next_action(self):
        return self.ACTION.get(self.status)

choices=Status without .choices at the end is the simplified form Django 5.0 accepts7. The whole workflow is one dictionary, NEXT. The ORM chapter covers the fields and relationships in depth.

Step 2: one function moves a card, safely

Two mechanics can press "Start repair" on the same card within the same second, or one impatient thumb can press twice. If the view simply moved the card "one step on", the second press would push it from in repair straight to ready, and the customer would hear their bike is ready while it is still on the stand. The fix is a conditional update: the form says which status the mechanic saw, and the database changes the row only if it still has that status.

# repairs/services.py
from django.utils import timezone

from .models import JobCard


class MoveRejected(Exception):
    """The move is not allowed, or someone else moved the card first."""


def move_card(card_id, from_status, workshop):
    to_status = JobCard.NEXT.get(from_status)
    if to_status is None:
        raise MoveRejected("This card cannot move any further.")
    # One SQL UPDATE with a WHERE on the old status: only one of two
    # simultaneous presses can succeed.
    changed = JobCard.objects.filter(
        pk=card_id, workshop=workshop, status=from_status
    ).update(status=to_status, updated_at=timezone.now())
    if changed == 0:
        raise MoveRejected("Someone else moved this card a moment ago.")
    return to_status

Two details matter. update() runs a single SQL statement and returns the number of rows it changed14. And it does not call save(), so auto_now does not fire. That is why updated_at is set by hand14. Forget it, and the live updates in the next section never notice the move.

This function is the heart of my rule from the start of the chapter. The htmx view calls it. The API for the mechanics app, later in this chapter, calls the same function. The workflow lives in one place.

Step 3: the views

# repairs/views.py
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, redirect, render
from django.views.decorators.http import require_GET, require_POST
from django.views.decorators.vary import vary_on_headers

from workshops.models import Workshop

from .models import JobCard
from .services import MoveRejected, move_card


def board_context(workshop):
    cards = list(
        JobCard.objects.filter(workshop=workshop)
        .exclude(status=JobCard.Status.COLLECTED)
        .select_related("booking", "mechanic")  # avoid one query per card
        .order_by("updated_at")
    )
    columns = [
        (value, label, [c for c in cards if c.status == value])
        for value, label in JobCard.Status.choices
        if value != JobCard.Status.COLLECTED
    ]
    return {"workshop": workshop, "columns": columns}


@login_required
@require_GET
@vary_on_headers("HX-Request")
def board(request, workshop_id):
    workshop = get_object_or_404(Workshop, pk=workshop_id)
    template = "repairs/_board.html" if request.htmx else "repairs/board.html"
    return render(request, template, board_context(workshop))


@login_required
@require_POST
def move(request, workshop_id, card_id):
    workshop = get_object_or_404(Workshop, pk=workshop_id)
    try:
        move_card(card_id, request.POST.get("from_status"), workshop)
    except MoveRejected as problem:
        messages.warning(request, str(problem))
    if request.htmx:
        # Answer with the fresh board, which htmx swaps into the page.
        return render(request, "repairs/_board.html", board_context(workshop))
    # Without JavaScript: the classic redirect after POST.
    return redirect("repairs:board", workshop_id=workshop.pk)

vary_on_headers("HX-Request") tells any cache between the browser and the server that the same URL returns different content depending on that header15. Without it, a cache could hand a full page request the bare fragment, or the other way round.

Whether this mechanic may move cards in this workshop at all is an authorisation question. The chapter on authentication and permissions in Django, the one after next in this series, adds that check. Here, being logged in is enough.

Step 4: the templates

The full page only wraps the fragment:

{# repairs/templates/repairs/board.html #}
{% extends "base.html" %}
{% block title %}{{ workshop.name }}: workshop board{% endblock %}
{% block content %}
  <h1>{{ workshop.name }}: workshop board</h1>
  {% include "repairs/_board.html" %}
{% endblock %}

The fragment is where htmx lives:

{# repairs/templates/repairs/_board.html #}
<div id="board"
     hx-get="{% url 'repairs:board' workshop.pk %}"
     hx-trigger="every 10s"
     hx-swap="outerHTML">

  <div role="status">
    {% for message in messages %}<p>{{ message }}</p>{% endfor %}
  </div>

  {% for value, label, cards in columns %}
    <section aria-labelledby="column-{{ value }}">
      <h2 id="column-{{ value }}">{{ label }} ({{ cards|length }})</h2>
      <ul>
        {% for card in cards %}
          <li>
            <p>{{ card.booking.problem|truncatewords:8 }}</p>
            <p>{{ card.mechanic|default:"Not assigned" }}</p>
            <form method="post"
                  action="{% url 'repairs:move' workshop.pk card.pk %}"
                  hx-post="{% url 'repairs:move' workshop.pk card.pk %}"
                  hx-target="#board"
                  hx-swap="outerHTML">
              {% csrf_token %}
              <input type="hidden" name="from_status" value="{{ card.status }}">
              <button type="submit">{{ card.next_action }}</button>
            </form>
          </li>
        {% empty %}
          <li>No cards.</li>
        {% endfor %}
      </ul>
    </section>
  {% endfor %}
</div>

Read it from the outside in:

  • The outer div has the id board. Every 10 seconds, hx-trigger="every 10s" asks the board URL for a fresh copy and hx-swap="outerHTML" replaces the whole div with it. htmx's docs show exactly this polling pattern9.
  • The role="status" region is announced by screen readers when its text changes, so "Someone else moved this card a moment ago" is heard, not only seen.
  • Each column is a section with a real heading, so a screen reader user can jump between columns.
  • Each card has a real <form> with method and action. Without JavaScript it posts and redirects. With htmx, hx-post sends the same form in the background and swaps the answer into #board. The hidden from_status is what makes the conditional update in step 2 work.

The base template loads htmx from your own static files. I prefer that over a public content delivery network for an internal tool: one fewer outside dependency, and no third party sees your staff's traffic.

{# templates/base.html #}
{% load static %}
<!doctype html>
<html lang="en-IE">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>{% block title %}Freewheel Cycles{% endblock %}</title>
  <script src="{% static 'vendor/htmx-1.9.12.min.js' %}" defer></script>
</head>
<body hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'>
  <main>{% block content %}{% endblock %}</main>
</body>
</html>

Step 5: URLs and settings

# repairs/urls.py
from django.urls import path

from . import views

app_name = "repairs"
urlpatterns = [
    path("workshops/<int:workshop_id>/board/", views.board, name="board"),
    path("workshops/<int:workshop_id>/cards/<int:card_id>/move/", views.move, name="move"),
]
# freewheel/settings.py (the parts that matter here)
INSTALLED_APPS = [
    # ... Django's own apps ...
    "django_htmx",
    "workshops",
    "bookings",
    "repairs",
]

MIDDLEWARE = [
    # ... Django's default middleware, including CsrfViewMiddleware ...
    "django_htmx.middleware.HtmxMiddleware",  # adds request.htmx
]

Then pip install django-htmx, download htmx 1.9.12 into static/vendor/, and run the server.

What happens when a mechanic presses "Start repair"

Follow one press from finger to screen, with no step skipped:

  1. A mechanic's phone shows the board. A card for a gravel bike with slipping gears sits under "Waiting". Its form holds from_status=waiting.
  2. The mechanic taps "Start repair". htmx catches the submit, sends POST /workshops/3/cards/812/move/ with the form fields, the CSRF token and the header HX-Request: true.
  3. Django's CSRF middleware checks the token. The move view calls move_card(812, "waiting", workshop).
  4. The database runs one UPDATE ... WHERE id = 812 AND workshop_id = 3 AND status = 'waiting'. One row changes.
  5. The view sees request.htmx is true and renders _board.html with fresh data. The card is now under "In repair" and its button says "Mark ready".
  6. htmx replaces #board on that phone. That took one round trip.
  7. Within 10 seconds, the wall screen and every other phone poll the board URL and swap in the same fresh fragment.

If a colleague had tapped the same card a moment earlier, step 4 changes zero rows, move_card raises MoveRejected, the warning goes into the messages, and the board comes back showing the card where the colleague left it, with "Someone else moved this card a moment ago" announced in the status region.

The whole interactive board is about 140 lines of Python and HTML, in one codebase, with one copy of the workflow.

Live updates: polling first, server sent events when it pays

"Every 10 seconds" sounds crude. It is worth doing the sums before replacing it with something cleverer.

The load polling puts on the server is a rate: screens divided by the interval.

r=ntr = \frac{n}{t}

rr is the number of board requests per second, nn the number of open boards, and tt the polling interval in seconds. Foundations: ratios and rates

The delay before a screen shows a move depends on when in the cycle the move happens. On average it is half the interval:

dˉ=t2\bar{d} = \frac{t}{2}

dˉ\bar{d} is the average delay in seconds between a move and another screen showing it, and tt again the polling interval. Foundations: the mean

Example: the polling sums for six workshops

Take the worst case at Freewheel, derived from the example's numbers: a wall screen in each of six workshops, a manager's screen in each, and all 38 mechanics with the board open on a phone. That is n=6+6+38=50n = 6 + 6 + 38 = 50 boards.

With t=10t = 10:

r=5010=5 requests per secondr = \frac{50}{10} = 5 \text{ requests per second}

Five requests a second, each answered by one query thanks to select_related, is light work for a single small server. Grand, in other words. The average delay is dˉ=10/2=5\bar{d} = 10 / 2 = 5 seconds, which nobody standing at a workbench will notice.

Now the waste. Each job card moves three times in its life (waiting to in repair, in repair to ready, ready to collected), so about 1,150 bookings a week produce about 1,150×3=3,4501{,}150 \times 3 = 3{,}450 moves. Assume the workshops are open six days a week for 10 hours (my assumption for the example), which gives 6×6×10=3606 \times 6 \times 10 = 360 workshop hours a week. That is about 3,450/360≈9.63{,}450 / 360 \approx 9.6 moves per workshop per hour. One screen polling every 10 seconds asks 360 times an hour. So roughly 350 of every 360 answers say "nothing changed", about 97%.

Polling every 10 seconds sends 360 requests an hour, polling every 30 seconds sends 120, and server sent events deliver about 10 messages an hour, one per card move in that workshop. Tap or click to enlarge

My view: at Freewheel's scale, keep polling. 97% wasted answers cost five small requests a second. Polling needs nothing beyond what you already run, it recovers on its own after a phone loses signal, and it is trivially testable. Move on when the numbers change: hundreds of open screens, an interval under two seconds, or a board query that has grown slow.

One honest weakness of polling with outerHTML swaps: if a mechanic is tabbing through the buttons with a keyboard when the board refreshes, focus is lost. Two fixes exist. The idiomorph extension, from the htmx authors, morphs the new HTML into the old instead of replacing it, which keeps focus and scroll position16. Or refresh only on a signal, which is where server sent events come in.

Example: the board over server sent events

Server sent events (SSE) are a plain HTTP response that never ends. The server keeps writing small text messages into it, and the browser's EventSource reads them as they arrive. htmx 1.9 supports SSE through its sse extension17.

The trick that keeps this simple: the stream does not carry HTML. It carries one word, "something changed", and the board then fetches itself through the view you already have.

{# Inside board.html, around the include #}
<script src="{% static 'vendor/htmx-ext-sse-1.9.12.js' %}" defer></script>
<div hx-ext="sse" sse-connect="{% url 'repairs:events' workshop.pk %}">
  <div hx-get="{% url 'repairs:board' workshop.pk %}"
       hx-trigger="sse:board_changed"
       hx-target="#board"
       hx-swap="outerHTML"></div>
  {% include "repairs/_board.html" %}
</div>

Remove hx-trigger="every 10s" from _board.html when you switch. The event stream is an asynchronous view:

# repairs/events.py
import asyncio

from django.db.models import Max
from django.http import HttpResponseForbidden, StreamingHttpResponse

from .models import JobCard


async def board_events(request, workshop_id):
    user = await request.auser()  # async access to the logged in user, new in Django 5.0
    if not user.is_authenticated:
        return HttpResponseForbidden()

    async def stream():
        last_seen = None
        while True:
            result = await JobCard.objects.filter(workshop_id=workshop_id).aaggregate(latest=Max("updated_at"))
            if result["latest"] != last_seen:
                last_seen = result["latest"]
                yield "event: board_changed\ndata: refresh\n\n"
            await asyncio.sleep(2)

    return StreamingHttpResponse(stream(), content_type="text/event-stream")

Add path("workshops/<int:workshop_id>/events/", events.board_events, name="events") to the URLs.

Three facts from the Django docs decide whether this is a good idea for you:

  • Django 4.2 added support for asynchronous iterators in StreamingHttpResponse. Under ASGI, the Asynchronous Server Gateway Interface, an open stream need not stop other requests being served while it waits18.
  • Under WSGI, the older synchronous Web Server Gateway Interface, a streaming response ties up a worker process for its whole duration, and Django's docs warn this may perform poorly18. Fifty open boards would hold fifty workers. So SSE means running Django under an ASGI server such as Daphne or Uvicorn19.
  • login_required is not in Django 5.0's list of decorators that support async views, while request.auser() is new in 5.07. That is why the view checks the user by hand.

Notice what the stream still does: it asks the database every two seconds. For 50 screens that is 25 small queries a second, more than the 10 second polling. You gained instant updates and lost nothing in correctness, but you did not save load. To save load you need a real push: when move_card succeeds, publish a message, and let the streams wait for it. That needs something every server process can hear, such as Redis or PostgreSQL's LISTEN and NOTIFY. It is real infrastructure, and the reason I start with polling.

WebSockets with Django Channels

If the board needs messages in both directions, for example a mechanic's phone sending live progress while a manager types a note, the tool is WebSockets, and in Django that means Channels. Channels wraps Django's async support so a project can handle protocols with long running connections, not only HTTP20. Messages between processes go through a channel layer, with Redis as the officially maintained backend through the channels_redis package21. Channels 4.1.0 came out on 3 April 202422.

My view: the workshop board is a one way problem. The server knows something changed and the screens need to know. That is what SSE is for. Reach for Channels when the browser has to talk back continuously, not because WebSockets sound more serious.

How this maps to Hotwire in Rails

Rails developers reading this will recognise most of it. Hotwire, the default front end approach in Rails 7, is built on the same idea: the server sends HTML, not JSON. htmx is the closest Django equivalent, with one real difference. Hotwire comes with Rails and its generators, while htmx in Django is a choice you add yourself. That makes Rails the more integrated path and Django the more explicit one, which is a fair summary of the two frameworks in general.

What you wantRails with HotwireDjango with htmx
Links and forms without full page reloadsTurbo Drive, on by defaulthx-boost on a container
Replace one part of the pageTurbo Framehx-target plus a fragment template
Change several parts from one responseTurbo Streamshx-swap-oob (out of band swap)
Keep focus and scroll while refreshingTurbo 8 page refresh with morphingidiomorph extension
Push changes to every open screenTurbo Streams broadcast over Action CableSSE extension, or Channels for WebSockets
Small client behaviour (toggle, copy, sort)Stimulus controllersPlain JavaScript, or a small library such as Alpine.js
Render one fragment by namePartials (_card.html.erb)Include files, or django template partials

Sources for the right hand column are the htmx docs and the packages named above. For the left, the Turbo handbook23 and the Turbo 8 release announcement of 7 February 2024, which introduced page refreshes by morphing24.

Example: the same board in both spikes

In the Rails version of Freewheel's spike, a card move answers with Turbo Streams and every open board receives the change as a broadcast over Action Cable, Rails' built in WebSocket layer. The Rails spike gets push updates for very little code, because Action Cable and the broadcasting helpers come with the framework.

In the Django version above, the same move answers with a fresh fragment, and other screens catch up by polling. Push is a second step (SSE, then a publish channel) that the Django team adds and runs deliberately.

Neither is wrong. For this board at this size, both spikes give a mechanic the same experience. The difference shows up in what the team has to assemble: in Rails it was there on day one, in Django they choose each piece, and they know exactly what each piece does. When Aisling and Cian scored the spikes, this was one of the points that tipped the matrix towards Rails for a small team. It would not tip it for a team that already runs Redis and Channels in other Django projects.

Option three: an API behind a JavaScript front end

The third route turns Django into a data server. A separate front end, usually React, Vue or Svelte, runs in the browser, calls JSON endpoints, and builds the page itself. In Django there are two main ways to build those endpoints.

Django REST Framework (DRF) is the long established choice. Version 3.15.1, from 22 March 2024, is current25. Its building blocks, each documented in its API guide:

  • Serializers turn model instances into JSON and validate incoming JSON, much as forms do for HTML26.
  • ViewSets group the actions on one resource (list, retrieve, create, update) in one class, and @action adds custom ones such as "move"27.
  • Routers generate the URL patterns for a viewset automatically28.
  • Authentication classes identify the caller. Session authentication reuses Django's login cookie and enforces CSRF for authenticated requests. Token authentication suits client server setups such as native mobile apps, and DRF's docs insist a token API is only served over HTTPS29.
  • Throttling limits how often a client may call. DRF's own docs warn that it is not a security measure against brute force or denial of service attacks, only basic protection against overuse30.

Django Ninja is the younger alternative, at version 1.1 since December 202331. It builds an API from Python type hints, validates with Pydantic and produces an OpenAPI schema automatically32. Teams that know FastAPI tend to feel at home in it. DRF has the larger ecosystem of add ons and many more answered questions online. Both are sound choices.

What the API route really costs

An API with a separate front end is the right answer in some situations. It is never free. These are the costs, each one concrete.

Two codebases. The front end is its own project: its own language (JavaScript or TypeScript), its own dependencies, its own build toolchain (Node.js, a package manager, a bundler), its own tests, its own release. Someone keeps both up to date, forever.

Duplicated validation. As counted at the start: the model, the serializer, and the JavaScript form each want a copy of the rules. DRF's decision not to call Model.clean() was deliberate and documented, for a cleaner separation3. It is a sensible design. It still means one more copy.

Authentication across origins. If the front end is served from app.freewheelcycles.example and the API from api.freewheelcycles.example, the browser treats them as different origins. You then need cross origin resource sharing (CORS) headers, usually through Adam Johnson's django-cors-headers package33, the front end's origin in Django's CSRF_TRUSTED_ORIGINS setting5, and careful cookie settings, or you switch to tokens and take on storing them safely in the browser. Serving everything from one origin avoids most of this, and many teams do exactly that.

Search engines and the first page load. A page that only exists after JavaScript runs reaches Google in two phases: crawled first, rendered later from a queue, which Google says can take longer than a few seconds. Google's own guidance still calls server side rendering or pre rendering a great idea, and notes that not every bot runs JavaScript34. For public pages, that usually means adding a rendering server such as Next.js, Nuxt or SvelteKit. For a board behind a login, it does not matter at all.

Example: the booking rule, counted again

Picture Freewheel building the customer booking page as a React application on top of DRF. The rule "a booking must be in the future" now lives:

  1. in Booking.clean(), because the managers still use the Django admin, and the admin runs it;
  2. in BookingSerializer.validate_starts_at(), because the serializer does not call clean();
  3. in the React form, so the customer sees the error before submitting.

Then Niamh decides that bookings must be at least two hours ahead, so the mechanics can plan. In the templates version, Aisling changes one line in clean() and one test. In the API version, she changes three places in two languages and their tests, and if the React release goes out a day after the Django release, the form and the server disagree for a day. Customers see "booking failed" on a time the form said was fine.

You can reduce the copies: put the rule in a plain Python function and call it from both clean() and the serializer, and let the React form show the server's error instead of checking first. Good teams do that. It is discipline you pay for every day, rather than a property the architecture gives you.

The API for the mechanics app, outlined

Here my rule pays off. Freewheel plans a small mobile app for mechanics. That is the second client, and the moment to add an API, next to the htmx board, not instead of it.

Example: the mechanics app API with Django REST Framework

The serializers describe what the app sees and what it may send:

# repairs/api/serializers.py
from rest_framework import serializers

from repairs.models import JobCard


class JobCardSerializer(serializers.ModelSerializer):
    problem = serializers.CharField(source="booking.problem", read_only=True)

    class Meta:
        model = JobCard
        fields = ["id", "status", "problem", "mechanic", "updated_at"]
        read_only_fields = fields


class MoveSerializer(serializers.Serializer):
    from_status = serializers.ChoiceField(choices=JobCard.Status.choices)

The viewset lists the cards of the mechanic's own workshop and adds a move action that calls the same move_card function as the htmx view:

# repairs/api/views.py
from rest_framework import permissions, status, viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.throttling import ScopedRateThrottle

from repairs.models import JobCard
from repairs.services import MoveRejected, move_card

from .serializers import JobCardSerializer, MoveSerializer


class JobCardViewSet(viewsets.ReadOnlyModelViewSet):
    serializer_class = JobCardSerializer
    permission_classes = [permissions.IsAuthenticated]
    throttle_classes = [ScopedRateThrottle]
    throttle_scope = "mechanics_app"

    def get_queryset(self):
        # Assumes each Mechanic is linked to a user account (see the auth chapter).
        workshop = self.request.user.mechanic.workshop
        return JobCard.objects.filter(workshop=workshop).select_related("booking")

    @action(detail=True, methods=["post"])
    def move(self, request, pk=None):
        card = self.get_object()
        payload = MoveSerializer(data=request.data)
        payload.is_valid(raise_exception=True)
        try:
            move_card(card.pk, payload.validated_data["from_status"], card.workshop)
        except MoveRejected as problem:
            # 409 Conflict: the app should reload the card and show the message.
            return Response({"detail": str(problem)}, status=status.HTTP_409_CONFLICT)
        card.refresh_from_db()
        return Response(JobCardSerializer(card).data)

The router and the settings:

# freewheel/urls.py (excerpt)
from django.urls import include, path
from rest_framework.routers import DefaultRouter

from repairs.api.views import JobCardViewSet

router = DefaultRouter()
router.register(r"job-cards", JobCardViewSet, basename="jobcard")

urlpatterns = [
    path("api/v1/", include(router.urls)),
    # ... the HTML views stay exactly as they are ...
]
# freewheel/settings.py (excerpt)
INSTALLED_APPS += ["rest_framework", "rest_framework.authtoken"]

REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "rest_framework.authentication.TokenAuthentication",
    ],
    "DEFAULT_THROTTLE_RATES": {"mechanics_app": "120/minute"},
}

After python manage.py migrate creates the token table, the app sends Authorization: Token <key> with every request29. POST /api/v1/job-cards/812/move/ with {"from_status": "waiting"} moves the card, exactly as the button on the board did.

Count what was added: two serializers, one viewset, a router, and token settings. Count what was not: no second copy of the workflow, no change to the htmx board, no CORS (a mobile app is not a browser, so the browser's same origin rules do not apply to it). The rate of 120 calls a minute per mechanic is my starting figure for a phone that polls, not a documented recommendation.

Example: the same endpoint with Django Ninja

For comparison, the move endpoint in Django Ninja is a typed function:

# repairs/api/ninja.py
from django.shortcuts import get_object_or_404
from ninja import NinjaAPI, Schema
from ninja.security import django_auth

from repairs.models import JobCard
from repairs.services import MoveRejected, move_card

api = NinjaAPI(auth=django_auth)


class MoveIn(Schema):
    from_status: JobCard.Status


@api.post("/job-cards/{card_id}/move", response={200: dict, 409: dict})
def move(request, card_id: int, data: MoveIn):
    card = get_object_or_404(JobCard, pk=card_id, workshop=request.user.mechanic.workshop)
    try:
        new_status = move_card(card.pk, data.from_status, card.workshop)
    except MoveRejected as problem:
        return 409, {"detail": str(problem)}
    return 200, {"id": card.pk, "status": new_status}

django_auth uses the session cookie, which suits a browser. For the phone app you would plug in a token scheme instead. The shape is the point: the type hint on from_status does the validation, and the function calls the same move_card.

The three approaches side by side

Templates and formsTemplates plus htmxAPI plus JavaScript front end
Who builds the HTMLDjangoDjangoThe JavaScript application
CodebasesOneOneTwo (or more)
Copies of a business ruleOneOneUsually two or three
LoginDjango sessionDjango sessionSession on one origin, or tokens
InteractivityPage per actionParts of the page updateAnything the browser can do
Live updatesNonePolling, SSE, ChannelsPolling, SSE, WebSockets
Search enginesFull HTML at onceFull HTML at onceNeeds server side rendering for public pages
Skills neededPython, HTMLPython, HTML, a little htmxPython plus JavaScript or TypeScript and a framework
Weak atAnything that movesOffline use, very frequent client state, spreadsheet style screensSmall teams, many shared rules, public content

To make "moving parts" concrete, I counted them from a fixed list of twelve: the Django project, server rendered templates, the htmx file, the django htmx middleware, an API layer, token authentication, a separate front end codebase, a JavaScript build toolchain, client side routing and state, CORS and cross origin cookies, a rendering server for public pages, and an API schema with versioning. A separate mobile app codebase counts as a separate front end codebase. The counts are mine, from that list.

Templates only need 2 moving parts, templates plus htmx need 4, a single page application on the same domain needs 6, the htmx web application plus an API for a mobile app needs 8, and a single page application on its own domain with server side rendering needs 10. Tap or click to enlarge

How the counts come out:

  • Templates only (2): Django project, templates.
  • Templates and htmx (4): plus the htmx file and the middleware.
  • SPA on the same domain (6): Django project, API layer, front end codebase, build toolchain, client routing and state, API schema. Sessions still work, so no tokens and no CORS.
  • htmx web plus mobile API (8): the four of the htmx route, plus API layer, token authentication, API schema, and the mobile app as a separate codebase.
  • SPA on its own domain with server side rendering (10): the SPA's six, plus token or cross origin authentication, CORS and cookies, a rendering server, and templates still kept for the login pages and emails.

The fourth bar is where Freewheel will be in a year. It is twice the moving parts of the htmx route, but each part was added for a client that exists.

Choosing, screen by screen

The decision is rarely one answer for the whole project. Decide per screen, and ask the questions in this order.

Tap or click to enlarge

Three situations push the whole project towards a JavaScript front end, and I would not argue with any of them: the product must work offline, its core screen is something like a spreadsheet or a map where every change ripples through the screen at once (the htmx authors name these same cases as a poor fit for their own tool1), or the team is mostly front end developers with a design system already built in React.

Example: Freewheel's screens, one by one

  • Customer booking form: does not change while you watch. Plain templates and forms, with htmx at most to check a slot as soon as the time is picked.
  • Workshop board: changes while you watch. Templates plus htmx, polling every 10 seconds.
  • Job card photos: an upload form. Plain templates (the next chapter in this series covers files).
  • Parts stock and the nightly reorder report: tables and filters. Templates plus htmx for the filters.
  • Manager back office: the Django admin first, as the admin chapter explains, then custom pages where it runs out.
  • Invoices with VAT at 23%: server rendered HTML, and a PDF from the same template.
  • Mechanics app (later): a second client. DRF API, calling the same service functions.
  • Parts demand forecast (later): a separate Python service that reads data, not a screen at all.

Not one screen needs offline use or per pointer reactions. Every one is either a form, a table, or a board that updates a few times an hour. Cian's React experience is not wasted: it goes into the mechanics app, the one place where a JavaScript codebase earns its keep.

For the person paying for this

If you are Niamh, here is what to ask when a developer proposes a front end:

  • "How many codebases will we maintain, and who keeps each one up to date?" Every codebase is a yearly cost in dependency updates and security patches, whether or not you add features.
  • "Where does the rule live?" Pick one real rule, such as "no bookings in the past", and ask to see every place it is enforced. One is ideal. Three needs a good reason.
  • "Which client is the API for?" If the answer is "for the future", ask which future, and when. An API built before its client usually has to be changed when the client finally arrives.
  • "What happens on a slow phone or with JavaScript off?" Server rendered pages still work. A pure SPA shows a blank page.
  • "Can a new developer change the board in their first week?" With templates and htmx, a Python developer can. With an SPA, they need both stacks.

None of these questions needs you to understand the code. They do need honest answers. If you want a second opinion on a proposal, or want to see how I approach this on Rails, my web application development page explains how I work.

My view

Documented: Django's templates, forms, CSRF protection and messages framework are mature and complete. htmx 1.9 adds partial page updates with HTML attributes and a request header. DRF and Django Ninja are both solid ways to build an API, and DRF deliberately keeps validation in the serializer rather than the model.

Community opinion: the htmx authors argue for hypermedia as the default for text, form and CRUD heavy applications, and say plainly where it does not fit135. Plenty of experienced teams prefer an SPA everywhere because one front end approach for the whole company is simpler to hire for and to standardise, and that is a legitimate trade off.

My judgement: for a business application like Freewheel's, run by a small team, templates plus htmx is the right default in Django, and an API is something you add for each new client that needs one. The test I use is the copy count. If a front end choice means keeping the same rule in more than one place, it needs a reason that the business can name. "It is more modern" is not one. "The mechanics app needs it" is.

Conclusion

Templates and forms give you one codebase, one copy of each rule, and secure defaults: escaping, CSRF tokens, messages and, since Django 5.0, accessible field groups. htmx adds the moving parts of a modern interface without a second codebase. The workshop board, with conditional updates and polling, is about 140 lines, and server sent events or Channels are there when the numbers call for them. An API behind React, Vue or Svelte is the right tool for offline products, spreadsheet like screens and front end led teams, and it costs two codebases, extra copies of your rules and work on authentication and search engines.

So count your clients and count your copies. Build the HTML for the browser, put the rules in models and plain functions, and add an API the day a second client arrives, calling the same functions. If you would like to work through that decision for your own project, book a free workshop: I sit down with you and map every screen to its clients.

If you are weighing templates against an API for your own application, book the free workshop: we map your screens and their clients together, and the first two weeks of work are on me.

Sources

  1. 1.

    Carson Gross, When Should You Use Hypermedia?, htmx.org essays, 23 October 2022, updated 3 February 2023, https://github.com/bigskysoftware/htmx/blob/v1.9.12/www/content/essays/when-to-use-hypermedia.md

  2. 2.

    Django Software Foundation, Creating forms from models, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/topics/forms/modelforms/

  3. 3.

    Tom Christie, Django REST Framework 3.0 announcement, section on model validation, Encode, 2014, https://www.django-rest-framework.org/community/3.0-announcement/

  4. 4.

    Django Software Foundation, The Django template language, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/ref/templates/language/

  5. 5.

    Django Software Foundation, How to use Django's CSRF protection, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/howto/csrf/

  6. 6.

    Django Software Foundation, The messages framework, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/ref/contrib/messages/

  7. 7.

    Django Software Foundation, Django 5.0 release notes, 4 December 2023, https://docs.djangoproject.com/en/5.0/releases/5.0/

  8. 8.
  9. 9.
  10. 10.

    htmx, Release v1.9.12, GitHub, 17 April 2024, https://github.com/bigskysoftware/htmx/releases/tag/v1.9.12

  11. 11.

    Adam Johnson, django htmx 1.17.3, Python Package Index, 1 March 2024, https://pypi.org/project/django-htmx/1.17.3/

  12. 12.

    Carlton Gibson, django template partials, GitHub, https://github.com/carltongibson/django-template-partials

  13. 13.

    Adam Johnson, django htmx documentation, Tips, https://django-htmx.readthedocs.io/en/latest/tips.html

  14. 14.

    Django Software Foundation, QuerySet API reference, update(), Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/ref/models/querysets/#update

  15. 15.

    Django Software Foundation, View decorators, vary_on_headers, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/topics/http/decorators/

  16. 16.

    Big Sky Software, idiomorph, GitHub, https://github.com/bigskysoftware/idiomorph

  17. 17.
  18. 18.

    Django Software Foundation, Request and response objects, StreamingHttpResponse, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/ref/request-response/

  19. 19.

    Django Software Foundation, How to deploy with ASGI, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/howto/deployment/asgi/

  20. 20.

    Django Channels, Introduction, Channels documentation, https://channels.readthedocs.io/en/stable/introduction.html

  21. 21.

    Django Channels, Channel layers, Channels documentation, https://channels.readthedocs.io/en/stable/topics/channel_layers.html

  22. 22.

    Django Software Foundation, channels 4.1.0, Python Package Index, 3 April 2024, https://pypi.org/project/channels/4.1.0/

  23. 23.

    Hotwire, Turbo Handbook, Introduction, 37signals, https://turbo.hotwired.dev/handbook/introduction

  24. 24.

    Alberto Fernández Capel, Turbo 8 released, 37signals Dev, 7 February 2024, https://dev.37signals.com/turbo-8-released/

  25. 25.

    Tom Christie and contributors, djangorestframework 3.15.1, Python Package Index, 22 March 2024, https://pypi.org/project/djangorestframework/3.15.1/

  26. 26.

    Django REST Framework, Serializers, API guide, https://www.django-rest-framework.org/api-guide/serializers/

  27. 27.

    Django REST Framework, ViewSets, API guide, https://www.django-rest-framework.org/api-guide/viewsets/

  28. 28.

    Django REST Framework, Routers, API guide, https://www.django-rest-framework.org/api-guide/routers/

  29. 29.

    Django REST Framework, Authentication, API guide, https://www.django-rest-framework.org/api-guide/authentication/

  30. 30.

    Django REST Framework, Throttling, API guide, https://www.django-rest-framework.org/api-guide/throttling/

  31. 31.

    Vitaliy Kucheryaviy, django ninja 1.1.0, Python Package Index, 7 December 2023, https://pypi.org/project/django-ninja/1.1.0/

  32. 32.

    Django Ninja, Documentation, https://django-ninja.dev/

  33. 33.

    Otto Yiu, Adam Johnson and contributors, django cors headers 4.3.1, Python Package Index, 14 November 2023, https://pypi.org/project/django-cors-headers/4.3.1/

  34. 34.

    Google Search Central, Understand the JavaScript SEO basics, Google, https://developers.google.com/search/docs/crawling-indexing/javascript/javascript-seo-basics

  35. 35.

    Carson Gross, Adam Stepinski and Deniz Akşimşek, Hypermedia Systems, 2023, https://hypermedia.systems/

Shelter

I’m running the London Marathon for Shelter. Sunday 25 April 2027

My personal fundraiser. Shelter, the National Campaign for Homeless People Limited, registered charity 263710 (England and Wales) and SC002327 (Scotland), registered with the Fundraising Regulator.

Donate to Shelter