Chapter 45 · HTMX and progressive enhancementCHAPTER 45
Complete six-part pre-release for review. No migrations. Two packages (django-htmx, and htmx through npm). Sign-in middleware moves to the accounts app as an htmx-aware subclass. No earlier test changes.
Working towards: Event-day operations (Chapter 46). Reminders sent in the background, a waitlist that offers released places, and check-in that records each attendance once. All milestones
CHAPTER FORTY-FIVE
HTMX and progressive enhancement
Stage 5: Growing the application (Chapters 35 to 46)
Prerequisites: Chapters 9 to 44, including the Chapter 44 project with its 541 passing tests, template partials ({% partialdef %}, Chapter 12, and the event list’s event-row, Chapter 36), the registration panel and Register and Cancel (Chapters 31 and 37), the questions formset (Chapter 38), sign-in by default (Chapter 39), and site.js with npm and Tailwind (Chapters 14 and 28)
What you’ll build: htmx 2.0.11, served by Otahque with its checksum recorded, and django-htmx for request.htmx; an event list whose filters and page links swap only the results; Register and Cancel that change the registration panel and the places count in place, with a dialog to confirm a cancel; an Add question button on the edit page; sign-in that works for htmx; and every page still working with JavaScript off
Why This Matters
Otahque works. Every page is a form or a link, and every press of a button loads a whole new page. On a laptop that is fine. On Sai’s phone, on a train, it is not: she ticks “Only events with places left”, presses Filter, and the whole list reloads, header and all, and she has lost her place on the page. She presses Register, and the page goes white, jumps to the top, and then says “You have a place” somewhere above where she was looking.
The usual answer is a JavaScript framework that draws the page in the browser and asks the server only for data. For Otahque that would mean writing every page twice, once as Django templates and once as JavaScript components, and keeping two sets of rules in step. There is a smaller answer. The server keeps sending HTML, as it always has; a small library, htmx, lets a button ask for one part of a page and put it in place. Everything that worked keeps working, and the pages where a reload hurts get better.
That is the idea of progressive enhancement: build the page so that it works with plain HTML, then add behaviour on top, so that if the script never loads, or a reader has turned it off, nothing is lost. This chapter applies it to three places: the event list, the registration panel, and the question builder.
By the end of the chapter, you will be able to:
explain progressive enhancement, and keep a page working without JavaScript while improving it with htmx;
make one view answer with a whole page or one named partial, and say why the answer must vary on a header;
swap two parts of a page from one response, with an out-of-band swap;
replace a redirect with a partial for htmx, and tell when a whole-page move needs HX-Redirect;
keep CSRF protection, sign-in, keyboard focus, and screen-reader announcements working when only part of a page changes;
defend serving a pinned script from your own site, and htmx over a JavaScript framework, for Otahque.
Out of scope: pages that update themselves when something changes on the server (Chapter 54), enforcing a Content Security Policy against this markup (Chapter 59), and htmx 4, which this chapter describes but does not use (N45.6).
What problem exists? A link or a form replaces the whole page, even when only a list or a panel changes.
What did people do before? Wrote JavaScript that fetched data and rebuilt that part of the page by hand, or moved the whole page into a JavaScript framework.
What is it?htmx is a JavaScript library of about 50 KB that reads attributes on your HTML. hx-get="/events/" on a form makes it ask for that address when the form is sent; hx-target="#results" says which element to replace; hx-swap="outerHTML" says how. The server answers with HTML, and htmx puts it in place. Every request it makes carries the header HX-Request: true.
Why use it? The server keeps the templates and the rules; the browser only places HTML. A page that has no htmx attributes, or a browser that never loads the script, behaves exactly as before.
Now let’s use it. Step 2 installs it, pinned, and serves it from Otahque.
htmx changes nothing on its own. The page must already work: the filter form must still have method="get", Register must still be a form that posts. htmx then intercepts the request, sends it in the background with HX-Request: true, and swaps in what comes back. So the view has to answer two kinds of request at one address: a browser loading the whole page, and htmx asking for one part of it. Figure 45.1 shows the event list doing both.
Figure 45.1 — One address, two answers.
Django already has the tool for “one part of a template”: the partials from Chapter 12. A {% partialdef results inline %} block is rendered in place on the whole page, and can also be rendered alone by naming it after the template, events/list.html#results. The view picks the name; the template holds both answers in one file.
New Tool: django-htmx
What problem exists? Each view would read request.headers.get('HX-Request') == 'true', and the other htmx headers, by hand, and build htmx’s response headers by name.
What did people do before? Exactly that, slightly differently in every project.
What is it?django-htmx, by Adam Johnson, a Django contributor, is a small package. Its middleware adds request.htmx to every request: false for an ordinary request, and for an htmx one, details such as request.htmx.target, the id of the element to be replaced. It also has response classes, such as HttpResponseClientRedirect, which tells htmx to load a whole new page. Version 1.29.0 supports Django 6.1, and was tried on Otahque’s Django 6.1.2 before this chapter (D45.3).
Why use it? One tested reading of htmx’s headers, used the same way in every view.
Now let’s use it. Step 3 adds the middleware and shows what it reads.
Two swaps from one answer
Register changes two places on the event page: the registration panel, where “Register” becomes “You have a place”, and the places count in the event’s facts, which drops by one. They are not next to each other, so one target cannot hold both. htmx’s answer is the out-of-band swap: the response holds the panel, which goes where hx-target says, and then another element marked hx-swap-oob="true". htmx finds the element on the page with the same id and replaces it too. Figure 45.2 follows one press of Register.
Figure 45.2 — Register with htmx.
Under the Hood: why a redirect breaks a swap
Since Chapter 31, Register answers with a redirect, 302 to the event page, and the browser follows it: Post, Redirect, Get. htmx makes its requests with the browser’s own fetching machinery, and that machinery follows redirects too, silently. So htmx never sees the 302: it sees the page at the end of it, the whole event page, header and footer, and puts it inside the panel, a page inside a page. Cancel is worse: it redirects to My registrations, so that whole page would land in the panel. The message “You have a place” is also stored for the next whole page, so it appears later, somewhere else. For htmx, the view must answer with the part itself, messages included; for a whole-page move, it sends the header HX-Redirect, and htmx loads that address in the window.
Still working without JavaScript
Progressive enhancement is a promise you can test. Without the HX-Request header, every view in this chapter answers exactly as it did in Chapter 44: Filter loads the page, Register redirects, Cancel goes to its confirmation page. The 541 tests you start with send no htmx headers, so they keep checking that path. Figure 45.3 puts the paths side by side.
Figure 45.3 — Three paths for one Register button.
Table 45.1 — The htmx attributes this chapter uses
Attribute
On
What it does
hx-get, hx-post
The filter form; Register and the cancel form
Send the request with htmx, to this address
hx-target
The same
The element to replace, such as #results
hx-swap
The same
How: outerHTML replaces the element; beforeend adds inside it, at the end
hx-push-url
The filter form
Put the new address in the address bar and history
hx-boost
Around the page links
Make plain links use htmx, keeping their href
hx-swap-oob
In an answer
Also replace the element with this id
hx-indicator
The filter form
Which elements get the htmx-request class while waiting
hx-disabled-elt
Forms
Disable the button while waiting, so it cannot be pressed twice
hx-include
Add question
Send this other field's value too
Three more things a swap must not break
CSRF. Since Chapter 24, every form that changes something carries {% csrf_token %}. htmx sends the form’s fields, token included, so Register and Cancel keep working with the check on. A request that is not a form needs the token in a header; Step 8 puts it on <body> for all of them, and tests both.
Signing in. Since Chapter 39, a signed-out request is redirected to sign in. For htmx that redirect is followed, and the sign-in page lands inside the panel. Step 7 makes Otahque’s sign-in middleware answer htmx with HX-Redirect, and fixes an older problem on the way: after signing in, the browser asks for next with GET, and the Register address only answers POST.
Focus and announcements. When a whole page loads, a screen reader starts reading it, and the keyboard starts at the top. When only a panel changes, neither happens unless the page says so. An `aria-live` region is an element whose changes a screen reader reads out; it has to be on the page before it changes, so it sits outside anything that is swapped. Otahque gets one such region, #live, in base.html, and moves focus to the panel’s heading after a swap.
New Concept: progressive enhancement
What problem exists? Scripts fail: a slow network, a blocked file, an old browser, a reader who turns JavaScript off. A page that needs its script then does nothing.
What did people do before? Built pages that only worked with their script, and showed an error otherwise; or built two versions.
What is it?Progressive enhancement means building the page from what every browser does, HTML forms and links, and adding behaviour only where the browser supports it. The enhancement changes how the page feels, never what it can do.
Why use it? Every member can register, whatever their browser; and the plain path is already tested.
Now let’s use it. Every step below keeps the plain path and its tests, and the Cancel dialog shows the idea twice over: the button that opens it appears only where the browser can open it.
Which htmx
htmx 4.0 was released on 28 August 2026, and 4.0.2 is current. Otahque uses htmx 2.0.11, for reasons recorded in N45.6 and Table 45.2. The htmx project publishes no long-term-support policy for either line; it says that htmx 2 “will continue to be supported indefinitely”, and it keeps 2.x as npm’s default version, latest, until early 2027. django-htmx 1.29.0 also defaults to 2.x and calls its 4.x support beta. Nearly every tutorial and answer you will find describes 2.x. htmx 4 changes defaults this chapter relies on, listed in the last column, so the choice is revisited when npm’s default or django-htmx’s moves to 4, and at the latest at the Django 6.2 upgrade.
Table 45.2 — htmx 2 and htmx 4, as they affect Otahque
Question
htmx 2.0.11 (Otahque)
htmx 4.0.2
npm's default (latest)
Yes, until early 2027
No: the next tag
Support
Supported indefinitely
Current major version
django-htmx 1.29.0
Default
Beta
Inheritance of attributes
Implicit
Explicit (hx-headers:inherited)
Error answers (4xx, 5xx)
Not swapped
Swapped
History
A cache of pages in the browser, which Otahque turns off
No cache
eval and inline handlers
allowEval, which Otahque turns off
allowEval removed
In practice: choosing a version of a library
Situation. A library has a new major version, and the old one is still supported.
Application. Read what the project says about support, see which version its package registry hands out by default, check the packages that wrap it, and look at what learners will find when they search. Pin one, and write down what would make you move.
Consideration. A new major version is not a reason by itself, and neither is an old one. Otahque records the trigger, npm’s default moving, so the upgrade is a decision with a date, not a surprise.
Start from Chapter 44, in the folder containing manage.py, with Otahque on PostgreSQL 18, 541 passing tests, and the work committed (the last commit is “Send emails from a worker; add reminders”). Two packages are new, django-htmx for Python and htmx itself through npm, so Step 2 needs an internet connection. There are no migrations. The new files are the served htmx file, five templates (the swapped panel, the cancel dialog, a spinner, a question row, and the htmx answer for Register and Cancel), six test modules, and a design note. The settings, the accounts middleware, the events and registrations views, the events URLs, base.html, the list, facts, panel, and questions templates, site.js, the stylesheet, package.json, and the lock files change. The visible result: filters, page links, Register, Cancel, and Add question work without reloading the page, and with JavaScript off everything works as before. The commands were checked in Windows PowerShell 5.1 and Git Bash against PostgreSQL 18.
The Custom Way
Without htmx, the usual move is a few lines of JavaScript per button: catch the form’s submit, call fetch(), take the HTML or JSON that comes back, and change the page with innerHTML. It works for one button. For the third, you are writing the same loop again, handling errors, disabling the button while waiting, keeping the address bar right, and remembering the CSRF token, each a little differently. htmx is that loop, written once and tested by many projects, driven by attributes. You still decide, in the view, which HTML comes back.
The Django Way
Step 1: Check the starting point
Terminal
uv run python manage.py test --parallel
Output
Found 541 test(s).
Creating test database for alias 'default'...
...
Ran 541 tests in ...s
OK
Terminal
git status --short
git log --oneline -1
Output
... Send emails from a worker; add reminders
Step 2: htmx, pinned and served by Otahque
The Python side first, pinned:
Terminal
uv add django-htmx==1.29.0
Output
Resolved 32 packages in ...
Installed 1 package in ...
+ django-htmx==1.29.0
Then htmx itself. Otahque already uses npm for Tailwind (Chapter 14), and npm records exactly what it installed in package-lock.json, with a checksum. Install the exact version as a development package, because the browser never reads node_modules:
PowerShell prints capitals and sha256sum small letters; the value is the same. If yours differs, you do not have the file this chapter was checked with: delete it and copy it again from node_modules.
In templates/base.html, above the line that loads site.js:
templates/base.html
{# Chapter 45: htmx, served by Otahque and pinned; no #}
{# copies of pages kept in the browser, no eval. #}
<meta name="htmx-config" content='{
"historyCacheSize": 0, "refreshOnHistoryMiss": true,
"allowEval": false, "allowScriptTags": false,
"includeIndicatorStyles": false}'>
<script src="{% static 'otahque/htmx-2.0.11.min.js' %}"
defer></script>
The htmx-config meta tag sets htmx’s options without any script on the page. historyCacheSize: 0 stops htmx keeping copies of pages in the browser’s storage, where an attendee list could otherwise sit after a member signs out; refreshOnHistoryMiss then makes Back load the page normally. allowEval and allowScriptTags off mean htmx never runs code that arrives in HTML, which Chapter 59’s security policy will require. includeIndicatorStyles off stops htmx adding a <style> element of its own: Otahque’s stylesheet will style the spinner. defer loads the file without holding up the page.
The test that the served file is the one you recorded, in a new file, config/tests/test_htmx_file.py:
config/tests/test_htmx_file.py
"""The htmx file Otahque serves (Chapter 45).
The file is copied from npm's package into static/otahque/
and pinned by its SHA-256, recorded in docs/design/htmx.md.
"""
import hashlib
from django.conf import settings
from django.test import TestCase
from django.urls import reverse
HTMX_FILE = 'otahque/htmx-2.0.11.min.js'
HTMX_SHA256 = ('d6fdc75f204e6bdefa99b69bf1e6d4ac'
'69b8a364f77929f45c13476b4000f717')
class HtmxFileTests(TestCase):
"""The pinned file, loaded on every page."""
def test_the_served_file_is_the_pinned_one(self):
path = settings.BASE_DIR / 'static' / HTMX_FILE
digest = hashlib.sha256(path.read_bytes()).hexdigest()
self.assertEqual(digest, HTMX_SHA256)
def test_every_page_loads_it_with_eval_off(self):
page = self.client.get(reverse('events:list'))
self.assertContains(page, HTMX_FILE)
self.assertContains(page, '"allowEval": false')
self.assertContains(page, '"historyCacheSize": 0')
Terminal
uv run python manage.py test config.tests.test_htmx_file
Output
Found 2 test(s).
Creating test database for alias 'default'...
...
Ran 2 tests in ...s
OK
Common Error: a script from a CDN
Many tutorials load htmx with <script src="https://unpkg.com/htmx.org">, with no version. That page then runs whatever that site serves today, from a server you do not control, and stops working offline. Otahque serves its own pinned copy, and a test notices if it changes (D45.2).
Step 3: What request.htmx reads
In config/settings.py, in MIDDLEWARE, below AuthenticationMiddleware:
config/settings.py
# request.htmx: whether htmx sent the request (45).
'django_htmx.middleware.HtmxMiddleware',
django-htmx does not need to be in INSTALLED_APPS: Otahque uses only its middleware and response classes, not its templates or static files. To see what the middleware reads, save this as seen.py next to manage.py:
seen.py
"""What htmx sends, and what request.htmx makes of it."""
from django.test import RequestFactory
from django_htmx.middleware import HtmxDetails
plain = RequestFactory().get('/events/')
swap = RequestFactory().get('/events/', headers={
'HX-Request': 'true', 'HX-Target': 'results'})
for request in (plain, swap):
htmx = HtmxDetails(request)
print(request.headers.get('HX-Request'), bool(htmx),
htmx.target)
Terminal
uv run manage.py shell -v 0 -c "exec(open('seen.py').read())"
Output
None False None
true True results
The plain request has no HX-Request header, and request.htmx is false. The htmx request has it, and request.htmx.target names the element it wants to replace. That is all the views below need. Delete seen.py.
Step 4: The list’s tests, first
The list must keep answering with the whole page, and answer htmx with the results alone. In a new file, events/tests/test_htmx.py:
events/tests/test_htmx.py
"""The event list's results, swapped by htmx (Chapter 45).
Without the HX-Request header the list answers with the
whole page; with it, and the results as the target, with
the results alone.
"""
from datetime import timedelta
from django.test import TestCase
from django.urls import reverse
from django.utils import timezone
from config.helpers import save_events
RESULTS = {'HX-Request': 'true', 'HX-Target': 'results'}
class ListSwapTests(TestCase):
"""The filters and page links swap only the results."""
@classmethod
def setUpTestData(cls):
save_events(13, timezone.now() + timedelta(days=1))
cls.address = reverse('events:list')
def test_without_htmx_the_whole_page(self):
page = self.client.get(self.address)
self.assertContains(page, '<html')
self.assertContains(page, 'id="results"')
def test_with_htmx_the_results_alone(self):
part = self.client.get(self.address, headers=RESULTS)
self.assertNotContains(part, '<html')
self.assertNotContains(part, '<h1>')
self.assertContains(part, 'id="results"')
self.assertContains(part, 'Event 012')
def test_page_links_swap_the_results_too(self):
part = self.client.get(self.address, {'page': 2},
headers=RESULTS)
self.assertContains(part, 'Event 013')
self.assertContains(part, 'hx-boost="true"')
def test_both_answers_vary_on_the_header(self):
page = self.client.get(self.address)
part = self.client.get(self.address, headers=RESULTS)
for response in (page, part):
self.assertIn('HX-Request', response['Vary'])
def test_going_back_in_history_gets_the_page(self):
page = self.client.get(self.address, headers=RESULTS | {
'HX-History-Restore-Request': 'true'})
self.assertContains(page, '<html')
def test_another_target_gets_the_page(self):
page = self.client.get(self.address, headers={
'HX-Request': 'true', 'HX-Target': 'main'})
self.assertContains(page, '<html')
Terminal
uv run python manage.py test events.tests.test_htmx
Output
Found 6 test(s).
Creating test database for alias 'default'...
FAIL: test_both_answers_vary_on_the_header
AssertionError: 'HX-Request' not found in 'Cookie'
FAIL: test_page_links_swap_the_results_too
AssertionError: False is not true : Couldn't find
'hx-boost="true"' in the following response
FAIL: test_with_htmx_the_results_alone
AssertionError: 1 != 0 :'<html' unexpectedly found in the
following response
... (1 more like these)
Ran 6 tests in ...s
FAILED (failures=4)
Two tests already pass: going back in history, and asking with another target, both get the whole page, as every request does now. The rest wait for the results to become a partial.
Step 5: The results as a partial
Replace events/templates/events/list.html with:
events/templates/events/list.html
{% extends "base.html" %}
{% block title %}Events | Otahque{% endblock %}
{% block content %}
<h1>Events</h1>
{# Chapter 45: htmx asks for the results alone and swaps #}
{# them in; without JavaScript the form loads the page. #}
<form method="get" class="filters"
hx-get="{% url 'events:list' %}" hx-target="#results"
hx-swap="outerHTML" hx-push-url="true"
hx-indicator="#results, #filter-spinner"
hx-disabled-elt="find button">
{% include "includes/show.html" %}
<input type="hidden" name="places" value="0">
<label class="flex items-center gap-2">
<input type="checkbox" name="places" value="1"
class="checkbox checkbox-sm"
{% if form.places_only %}checked{% endif %}>
Only events with places left
</label>
<button type="submit" class="btn btn-sm">
<span id="filter-spinner" aria-hidden="true"
class="htmx-indicator loading loading-spinner
loading-xs"></span>
Filter</button>
</form>
{% partialdef results inline %}
<div id="results" class="results">
{% if form.places_only %}
<p class="filter-note text-sm">
Showing only events with places left.
<a href="?places=0">Show all</a></p>
{% endif %}
{% regroup page_obj by over as groups %}
{% for group in groups %}
{% if group.grouper %}
<h2 class="list-heading mt-8">Past events</h2>
{% endif %}
<ul class="event-list event-cards
{% if group.grouper %}event-past{% endif %}">
{% for event in group.list %}
{% partialdef event-row inline %}
<li class="event-row event-card">
{% if event.cover %}
<img class="card-cover" src="{{ event.cover.url }}"
alt="" loading="lazy">
{% endif %}
<a class="event-title"
href="{% url 'events:detail' event.id %}">
{{ event.title }}
</a>
<span class="text-sm">
{% include "events/when.html" %}
</span>
<span class="event-badges">
{% if event.starts_at <= now %}
{% if now < event.ends_at %}
<span class="badge badge-primary">
Happening now
</span>
{% endif %}
{% endif %}
{% if now < event.ends_at %}
{% include "events/places.html" %}
{% endif %}
</span>
</li>
{% endpartialdef %}
{% endfor %}
</ul>
{% empty %}
<p class="event-empty event-card">
{% if form.parts or form.places_only %}
No events match these filters.
{% else %}
No upcoming events.
{% endif %}
</p>
{% endfor %}
{# The page links swap the results too, and scroll back #}
{# to their top. #}
<div hx-boost="true" hx-target="#results"
hx-swap="outerHTML show:#results:top"
hx-indicator="#results">
{% include "includes/pagination.html" %}
</div>
</div>
{% endpartialdef %}
{% endblock %}
Three things changed. The form gained htmx attributes, and keeps method="get": without htmx it loads the page as before. Everything below the form, the filter note, the groups, and the page links, is now inside {% partialdef results inline %} and one <div id="results">, so htmx has one element to replace. The page links sit inside an element with hx-boost="true", which makes plain links use htmx, keeping their href; show:#results:top scrolls to the top of the new results.
In events/views.py, add from django.utils.cache import patch_vary_headers below from django.utils import timezone, and in EventListView replace get() with:
events/views.py
def get(self, request, *args, **kwargs):
"""Read the filters, then let ListView do the rest.
The answer depends on the HX-Request header, so a
cache must keep the page and the results apart.
"""
self.now = timezone.now()
self.form = list_filters(request)
response = super().get(request, *args, **kwargs)
patch_vary_headers(response, ['HX-Request'])
return response
def get_template_names(self):
"""Return the results alone for htmx (Chapter 45).
Only a request that targets the results gets them
alone; going back in history gets the whole page.
"""
htmx = self.request.htmx
if (htmx and htmx.target == 'results'
and not htmx.history_restore_request):
return [f'{self.template_name}#results']
return super().get_template_names()
get_template_names() asks for list.html#results only when the request comes from htmx, targets the results, and is not a history restore, which htmx sends when the browser goes back to a page it has no copy of; that one must be whole. patch_vary_headers() adds Vary: HX-Request to both answers. Without it, a cache between Sai and Otahque, in her browser or on the network, could store the results alone under /events/ and later hand them out as the whole page.
The spinner in the button, and the dimmed results, need two rules. In static/otahque/source.css, at the top of @layer utilities:
static/otahque/source.css
/* While htmx waits (Chapter 45): a spinner, after
daisyUI's .loading, and the old results dimmed. */
.htmx-indicator {
display: none;
}
.htmx-request .htmx-indicator,
.htmx-request.htmx-indicator {
display: inline-block;
}
.results.htmx-request {
opacity: 0.55;
}
They sit in the utilities layer so they come after daisyUI’s own .loading rule, which would otherwise always show the spinner.
Terminal
npm run build
uv run python manage.py test events.tests.test_htmx
Output
Found 6 test(s).
Creating test database for alias 'default'...
...
Ran 6 tests in ...s
OK
Step 6: Register and Cancel in place
The tests first, in a new file, registrations/tests/test_panel.py:
registrations/tests/test_panel.py
"""Register and Cancel without leaving the page (Chapter 45).
With the HX-Request header the two views answer with the
panel, not a redirect; without it they answer as before.
"""
from django.test import TestCase
from accounts.models import Profile
from events.models import Event
from .test_registrations import soon, url, verified
HTMX = {'HX-Request': 'true'}
class PanelSwapTests(TestCase):
"""What htmx gets back from Register and Cancel."""
@classmethod
def setUpTestData(cls):
cls.event = soon()
cls.sai = verified('sai@example.org')
def setUp(self):
self.client.force_login(self.sai)
def register(self, **headers):
"""Press Register on the event page."""
return self.client.post(url('register', self.event.pk),
headers=headers)
def test_register_answers_with_the_panel(self):
response = self.register(**HTMX)
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response,
'registrations/swapped.html')
self.assertContains(response, 'id="registration-panel"')
self.assertContains(response, 'You have a place.')
self.assertNotContains(response, '<html')
def test_the_count_is_swapped_out_of_band(self):
response = self.register(**HTMX)
self.assertContains(
response, 'id="places-left"\n '
'hx-swap-oob="true"')
self.assertContains(response, '1 of 2 places left')
def test_the_message_is_not_left_for_the_next_page(self):
self.register(**HTMX)
page = self.client.get(self.event.get_absolute_url())
self.assertNotContains(page, 'alert-success')
def test_without_htmx_it_redirects_as_before(self):
response = self.register()
self.assertRedirects(response,
self.event.get_absolute_url())
def test_a_refusal_is_shown_in_the_panel(self):
Event.objects.filter(pk=self.event.pk).update(
capacity=1)
self.event.registrations.create(
member=verified('raj@example.org'))
response = self.register(**HTMX)
self.assertContains(response, 'This event is full.')
self.assertContains(response, 'alert-error')
def test_details_open_as_a_whole_page(self):
Event.objects.filter(pk=self.event.pk).update(
phone_required=True)
Profile.of(self.sai)
response = self.register(**HTMX)
self.assertEqual(response.status_code, 200)
self.assertEqual(response['HX-Redirect'],
url('details', self.event.pk))
def test_cancel_from_the_dialog_answers_with_the_panel(self):
self.register()
place = self.event.registrations.get()
response = self.client.post(url('cancel', place.pk),
headers=HTMX)
self.assertContains(response, 'Place cancelled.')
self.assertContains(response, '2 of 2 places left')
self.assertContains(response, 'hx-post="'
+ url('register', self.event.pk))
def test_cancel_from_its_page_still_redirects(self):
self.register()
place = self.event.registrations.get()
response = self.client.post(url('cancel', place.pk))
self.assertRedirects(response, url('mine'))
Terminal
uv run python manage.py test registrations.tests.test_panel
Output
Found 8 test(s).
Creating test database for alias 'default'...
FAIL: test_a_refusal_is_shown_in_the_panel
AssertionError: 302 != 200 : Couldn't retrieve content:
Response code was 302 (expected 200)
FAIL: test_cancel_from_the_dialog_answers_with_the_panel
AssertionError: 302 != 200 : Couldn't retrieve content:
Response code was 302 (expected 200)
FAIL: test_details_open_as_a_whole_page
AssertionError: 302 != 200
... (3 more like these)
Ran 8 tests in ...s
FAILED (failures=6)
In registrations/views.py, the imports become:
registrations/views.py
import logging
from django.contrib import messages
from django.core.exceptions import ValidationError
from django.http import StreamingHttpResponse
from django.shortcuts import (
get_object_or_404, redirect, render,
)
from django.urls import reverse
from django.utils import timezone
from django.utils.decorators import method_decorator
from django.views import View
from django.views.generic import (
DetailView, FormView, ListView,
)
from django.views.decorators.http import (
require_http_methods, require_POST,
)
from django_htmx.http import HttpResponseClientRedirect
from audit.models import AuditEvent, record
from events import emails
from events.models import REASONS, Event
from events.views import deny, page_numbers, registration_panel
from .forms import DetailsForm, MyPlacesForm
from .models import Registration
from .table import columns, csv_lines, extra_cells
Replace take_place() with a new function and the changed take_place():
registrations/views.py
def swapped_panel(request, event):
"""Render the event page's panel for htmx (Chapter 45).
It replaces the redirect, which htmx would follow and
swap a whole page into the panel. The messages are
shown in the panel and read out, so none is left over
for the next page.
"""
event = Event.objects.with_places().get(pk=event.pk)
context = {
'event': event, 'swapped': True,
'notes': list(messages.get_messages(request)),
} | registration_panel(event, request.user,
timezone.now())
return render(request, 'registrations/swapped.html',
context)
def take_place(request, event, answers=None):
"""Register the member, then say what happened.
If the event still needs a phone number or answers,
the member is sent to the details page: for htmx, as a
whole page (HX-Redirect).
"""
try:
place = event.register(request.user, timezone.now(),
answers)
except ValidationError as error:
codes = [e.code for e in error.error_list]
if set(codes) <= {'phone_missing', 'answers_needed'}:
details = reverse('registrations:details',
args=[event.pk])
if request.htmx:
return HttpResponseClientRedirect(details)
return redirect(details)
if codes == ['already_registered']:
messages.info(request, REASONS['already_registered'])
else:
if 'busy' in codes:
# The member will ask what went wrong: one
# line, with this request's id (Chapter 39).
log.warning('register busy: event %s',
event.pk)
for message in error.messages:
messages.error(request, message)
else:
messages.success(request, 'You have a place.')
emails.place_confirmed(place)
if request.htmx:
return swapped_panel(request, event)
return redirect(event)
and in CancelRegistrationView, replace post() with:
registrations/views.py
def post(self, request, *args, **kwargs):
"""Cancel the place, then say what happened."""
registration = self.get_object()
try:
changed = registration.cancel(timezone.now())
except ValidationError as error:
messages.error(request, error.messages[0])
else:
say_cancelled(request, registration, changed)
# From the event page's dialog (Chapter 45).
if request.htmx:
return swapped_panel(request, registration.event)
return redirect('registrations:mine')
swapped_panel() reads the event again with its places count, collects the messages, which marks them as used, so none is left for the next page, and renders a new template. registration_panel() is the function the event page itself uses since Chapter 31, so the panel shows exactly what the page would.
The new template, registrations/templates/registrations/swapped.html:
{# What htmx gets after Register or Cancel (Chapter 45): #}
{# the panel, the places left out of band, and the #}
{# messages for the live region, which reads them out. #}
{% include "registrations/panel.html" %}
{% include "events/facts.html#places-left" %}
<p id="live" hx-swap-oob="innerHTML">
{% for note in notes %}{{ note }} {% endfor %}</p>
It needs two things on the event page. In events/templates/events/facts.html, the places count becomes a partial with an id:
events/templates/events/facts.html
<dd>{% partialdef places-left inline %}
{# Chapter 45: replaced out of band after a swap. #}
<span id="places-left"
{% if swapped %}hx-swap-oob="true"{% endif %}>
{% include "events/places.html" %}</span>
{% endpartialdef %}</dd>
On the whole page, swapped is not set, so the <span> is plain; in the swap it carries hx-swap-oob="true". And in templates/base.html, above {% block page %}, the live region:
templates/base.html
{# Read out by screen readers when a part of the page #}
{# changes in place (Chapter 45). #}
<p id="live" class="sr-only" aria-live="polite"></p>
sr-only is Tailwind’s class for text that screen readers read and nobody sees. Replace registrations/templates/registrations/panel.html with:
registrations/templates/registrations/panel.html
{# Chapter 45: htmx swaps this whole section after #}
{# Register or Cancel; swapped is true only then. #}
<section id="registration-panel" class="registration-panel
space-y-3 rounded-box border border-base-300
bg-base-200 p-4" aria-labelledby="register">
<h2 id="register" class="text-lg font-semibold"
tabindex="-1" {% if swapped %}data-focus{% endif %}>
Registration</h2>
{% for note in notes %}
<div class="alert alert-{{ note.level_tag }}">
<span>{{ note }}</span></div>
{% endfor %}
{% if place %}
<p><span class="badge badge-success">You have a
place</span> Registered
{{ place.registered_at|date:"j M Y, H:i" }}.</p>
<p><a href="{% url 'registrations:cancel' place.pk %}">
Cancel my place</a></p>
{% elif reasons %}
<div class="alert alert-warning items-start"
role="status">
<div>
<p class="font-semibold">You cannot register now</p>
<ul class="list-disc pl-5">
{% for reason in reasons %}
<li>{{ reason }}</li>
{% endfor %}
</ul>
</div>
</div>
{% if unverified %}
<p><a href="{% url 'account_email' %}">Confirm your
email address</a>, then come back.</p>
{% endif %}
{% elif not user.is_authenticated %}
{% url 'account_login' as sign_in %}
{% with back=event.get_absolute_url|urlencode %}
<a class="btn btn-primary"
href="{{ sign_in }}?next={{ back }}">
Sign in to register</a>
{% endwith %}
{% elif needs_details %}
<a class="btn btn-primary"
href="{% url 'registrations:details' event.pk %}">
Register</a>
{% include "registrations/sharing.html" %}
{% else %}
{% url 'registrations:register' event.pk as register %}
<form method="post" action="{{ register }}"
hx-post="{{ register }}"
hx-target="#registration-panel" hx-swap="outerHTML"
hx-disabled-elt="find button">
{% csrf_token %}
<button type="submit" class="btn btn-primary">
{% include "includes/spinner.html" %}
Register</button>
</form>
{% include "registrations/sharing.html" %}
{% endif %}
{% if can_see_attendees %}
<p><a href="{% url 'registrations:attendees' event.pk %}">
Attendee list</a></p>
{% endif %}
</section>
The section has an id, registration-panel, and the Register form posts with htmx into it. notes are the messages, shown only in a swap. The spinner, in a new file templates/includes/spinner.html:
templates/includes/spinner.html
{# Shown while htmx waits for an answer (Chapter 45). #}
<span class="htmx-indicator loading loading-spinner
loading-xs" aria-hidden="true"></span>
Terminal
uv run python manage.py test registrations.tests.test_panel
Output
Found 8 test(s).
Creating test database for alias 'default'...
...
Ran 8 tests in ...s
OK
Common Error: a page inside a page
If a whole page appears inside the panel, with a second header and footer, a view answered htmx with a redirect, or with the whole template. Look at the response in the browser’s Network tab: an htmx request has HX-Request: true in its request headers, and its answer should start with the element you target, not <!doctype html>.
Step 7: Signed out, and htmx
A member’s session can end while the event page is open. Then Register is a signed-out POST. The test, in a new file, accounts/tests/test_htmx_sign_in.py:
accounts/tests/test_htmx_sign_in.py
"""Sign-in by default, answered for htmx (Chapter 45)."""
from django.test import TestCase
from registrations.tests.test_registrations import soon, url
HTMX = {'HX-Request': 'true'}
class SignedOutTests(TestCase):
"""A visitor, or a member whose session has ended."""
@classmethod
def setUpTestData(cls):
cls.event = soon()
cls.address = url('register', cls.event.pk)
def test_htmx_is_told_to_open_sign_in_as_a_page(self):
response = self.client.post(self.address,
headers=HTMX)
self.assertEqual(response.status_code, 200)
self.assertEqual(
response['HX-Redirect'],
f'/accounts/login/?next=/events/{self.event.pk}/',
)
def test_after_sign_in_a_post_goes_to_the_event(self):
response = self.client.post(self.address)
self.assertRedirects(
response,
f'/accounts/login/?next=/events/{self.event.pk}/',
fetch_redirect_response=False,
)
def test_a_get_keeps_its_own_address(self):
address = url('mine')
response = self.client.get(address)
self.assertRedirects(
response, f'/accounts/login/?next={address}',
fetch_redirect_response=False,
)
Terminal
uv run python manage.py test accounts.tests.test_htmx_sign_in
Output
Found 3 test(s).
Creating test database for alias 'default'...
FAIL: test_after_sign_in_a_post_goes_to_the_event
AssertionError:
'/accounts/login/?next=%2Fevents%2F1%2Fregister%2F' !=
'/accounts/login/?next=%2Fevents%2F1%2F'
FAIL: test_htmx_is_told_to_open_sign_in_as_a_page
AssertionError: 302 != 200
Ran 3 tests in ...s
FAILED (failures=2)
The first failure is the problem Figure 45.3 shows: htmx gets a redirect, follows it, and would put the sign-in page in the panel. The second is older: next is the Register address, and after signing in the browser asks for it with GET, which require_POST answers with 405. Both are fixed where Chapter 39 made the decision to send visitors to sign in: the middleware. Django’s LoginRequiredMiddleware has a method for exactly this, handle_no_permission().
In accounts/middleware.py, the docstring and imports become:
accounts/middleware.py
"""Middleware for the viewer's zone and for sign-in."""
from django.contrib.auth import middleware
from django.contrib.auth.views import redirect_to_login
from django.shortcuts import resolve_url
from django.urls import reverse
from django.utils import timezone
from django_htmx.http import HttpResponseClientRedirect
from .timezones import resolve_timezone
and at the end of the file:
accounts/middleware.py
class LoginRequiredMiddleware(
middleware.LoginRequiredMiddleware
):
"""Sign-in by default, for pages and for htmx (45).
After signing in, the browser asks for next with GET.
A POST to an event's address goes back to the event's
page instead, which answers GET. An htmx request is told
to load the sign-in page in the whole window.
"""
def handle_no_permission(self, request, view_func):
"""Send the visitor to sign in, then back to a page."""
event_id = request.resolver_match.kwargs.get('event_id')
if request.method == 'POST' and event_id:
back = reverse('events:detail', args=[event_id])
response = redirect_to_login(
back, resolve_url(self.get_login_url(view_func)),
self.get_redirect_field_name(view_func),
)
else:
response = super().handle_no_permission(request,
view_func)
if request.htmx:
# htmx would follow a redirect itself and swap the
# sign-in page into the panel. HX-Redirect makes
# the browser open it as a whole page.
return HttpResponseClientRedirect(response.url)
return response
It lives in the accounts app, which owns signing in. It cannot go in config/middleware.py: Django’s logging settings import that module before the apps are ready, and this class imports django.contrib.auth. In config/settings.py, the sign-in line in MIDDLEWARE becomes:
config/settings.py
# Every page needs sign-in unless its view is marked
# login_not_required (Chapter 39); since Chapter 45,
# Otahque's own subclass, which also answers htmx.
'accounts.middleware.LoginRequiredMiddleware',
Terminal
uv run python manage.py test accounts.tests.test_htmx_sign_in
uv run python manage.py test config.tests.test_public
Output
Found 3 test(s).
Creating test database for alias 'default'...
...
Ran 3 tests in ...s
OK
Found 3 test(s).
Creating test database for alias 'default'...
...
Ran 3 tests in ...s
OK
Chapter 39’s tests pass unchanged: they ask for every page with GET, and a GET keeps its own address as next.
Step 8: The CSRF token
Register and Cancel are forms, so htmx sends their csrfmiddlewaretoken field. A request that is not a form, such as a button with hx-post alone, has no field to send; Django also accepts the token in the X-CSRFToken header. In templates/base.html, the <body> line becomes:
templates/base.html
{# htmx sends the CSRF token with requests that are not #}
{# forms; a form sends its own field. #}
<body hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'>
hx-headers adds those headers to every htmx request from inside the element, and {{ csrf_token }} is the same token the forms use. Django’s test client skips the CSRF check unless told otherwise, so these tests turn it on. In a new file, registrations/tests/test_csrf.py:
registrations/tests/test_csrf.py
"""htmx and the CSRF check (Chapter 45)."""
from django.test import Client, TestCase
from .test_panel import HTMX
from .test_registrations import soon, url, verified
class CsrfTests(TestCase):
"""htmx sends the form's token, like the browser does."""
@classmethod
def setUpTestData(cls):
cls.event = soon()
cls.sai = verified('sai@example.org')
cls.address = url('register', cls.event.pk)
def setUp(self):
self.client = Client(enforce_csrf_checks=True)
self.client.force_login(self.sai)
def test_without_the_token_htmx_is_refused(self):
response = self.client.post(self.address,
headers=HTMX)
self.assertEqual(response.status_code, 403)
self.assertFalse(self.event.registrations.exists())
def test_with_the_page_token_htmx_registers(self):
page = self.client.get(self.event.get_absolute_url())
token = page.context['csrf_token']
response = self.client.post(
self.address, {'csrfmiddlewaretoken': token},
headers=HTMX,
)
self.assertContains(response, 'You have a place.')
Terminal
uv run python manage.py test registrations.tests.test_csrf
Output
Found 2 test(s).
Creating test database for alias 'default'...
...
Ran 2 tests in ...s
OK
Step 9: Focus and announcements
After a swap, the panel’s new heading carries data-focus. At the end of static/otahque/site.js:
static/otahque/site.js
// Chapter 45: after htmx swaps in part of a page, move
// the keyboard to the heading it marks with data-focus.
document.addEventListener('htmx:afterSettle', () => {
const heading = document.querySelector('[data-focus]');
if (heading) {
heading.removeAttribute('data-focus');
heading.focus();
}
});
htmx fires htmx:afterSettle once new content is in place. The heading has tabindex="-1", which lets a script focus it without adding it to the Tab order. The live region, filled in the same swap, is read out by a screen reader: “You have a place.” Check it yourself: register for an event with only the keyboard, using Tab and Enter, and see that focus lands on “Registration”; on Windows, turn on Narrator with Ctrl+Windows+Enter and listen for the message. No automated test can tell you what a person hears; the Playwright check in Step 12 confirms where focus lands and what the live region holds.
Step 10: Add question
On the edit page, the questions formset of Chapter 38 shows one blank question. To ask a second new one, Sam has to save and come back. With htmx, Add question asks the server for one more blank form, correctly numbered. The tests, in a new file, events/tests/test_question_rows.py:
events/tests/test_question_rows.py
"""Add question on the edit page (Chapter 45)."""
from datetime import timedelta
from django.test import TestCase
from django.urls import reverse
from django.utils import timezone
from audit.models import AuditEvent
from config.helpers import in_group, save_event
class QuestionRowTests(TestCase):
"""Add question: one more blank form, numbered."""
@classmethod
def setUpTestData(cls):
cls.sam = in_group('sam@example.org', 'Organizers')
cls.event = save_event(
starts_at=timezone.now() + timedelta(days=7))
cls.event.add_organizer(cls.sam)
cls.row = reverse('events:question_row',
args=[cls.event.pk])
def setUp(self):
self.client.force_login(self.sam)
def ask(self, count):
"""Press Add question with count forms on the page."""
return self.client.get(
self.row, {'questions-TOTAL_FORMS': count},
headers={'HX-Request': 'true'})
def test_the_new_form_takes_the_next_number(self):
response = self.ask(1)
self.assertContains(response, 'name="questions-1-label"')
self.assertNotContains(response, '__prefix__')
def test_the_count_goes_up_out_of_band(self):
response = self.ask(1)
self.assertContains(
response, 'id="id_questions-TOTAL_FORMS" value="2"')
self.assertContains(response, 'hx-swap-oob="true"')
def test_the_tenth_form_is_the_last(self):
tenth = self.ask(9)
self.assertContains(tenth, 'name="questions-9-label"')
self.assertContains(tenth, 'Ten questions is the most')
more = self.ask(10)
self.assertNotContains(more, 'questions-10-label')
def test_no_count_is_a_bad_request(self):
response = self.client.get(self.row)
self.assertEqual(response.status_code, 400)
def test_the_edit_page_offers_the_button(self):
page = self.client.get(reverse('events:edit',
args=[self.event.pk]))
self.assertContains(page, 'hx-get="' + self.row)
self.assertContains(page, 'class="needs-js"')
def test_someone_else_is_refused_and_recorded(self):
raj = in_group('raj@example.org', 'Organizers')
self.client.force_login(raj)
response = self.ask(1)
self.assertEqual(response.status_code, 403)
self.assertTrue(AuditEvent.objects.filter(
actor=raj, action='edit_event',
outcome='refused').exists())
Terminal
uv run python manage.py test events.tests.test_question_rows
Output
Found 6 test(s).
Creating test database for alias 'default'...
ERROR: setUpClass
django.urls.exceptions.NoReverseMatch: Reverse for
'question_row' not found. 'question_row' is not a valid
view function or pattern name.
Ran 0 tests in ...s
FAILED (errors=1)
A formset knows how many forms to read from its management form, a hidden field named questions-TOTAL_FORMS. A new form must be named with the next number, questions-1-label after questions-0-label, and the total must go up by one, or Django ignores the new form when the page is saved. Replace events/templates/events/questions.html with:
events/templates/events/questions.html
<fieldset class="form-section">
<legend>Questions for people who register</legend>
<p class="text-sm">Up to ten, answered when members
register. Ask only what you need to run the event:
never health details, ID numbers, or passwords, and an
age range rather than a date of birth.</p>
{{ questions.management_form }}
{{ questions.non_form_errors }}
<ol id="question-cards" class="question-cards">
{% for question in questions %}
{% partialdef question-card inline %}
<li class="question-card">
{% for hidden in question.hidden_fields %}
{{ hidden }}
{% endfor %}
{{ question.non_field_errors }}
<div class="form-grid">
{{ question.label.as_field_group }}
{{ question.kind.as_field_group }}
{{ question.choices.as_field_group }}
{{ question.help_text.as_field_group }}
{{ question.required.as_field_group }}
{% if question.instance.pk %}
{{ question.DELETE.as_field_group }}
{% endif %}
</div>
</li>
{% endpartialdef %}
{% endfor %}
</ol>
{# Chapter 45: one more blank question, numbered by the #}
{# server; without JavaScript, save to get another. #}
{% partialdef add-question inline %}
<p id="add-question" class="needs-js"
{% if swapped %}hx-swap-oob="true"{% endif %}>
{% if more_questions %}
<button type="button" class="btn btn-sm btn-outline"
hx-get="{% url 'events:question_row' event.pk %}"
hx-include="#id_questions-TOTAL_FORMS"
hx-target="#question-cards" hx-swap="beforeend">
{% include "includes/spinner.html" %}
Add question</button>
{% else %}
<span class="text-sm">Ten questions is the most an
event can ask.</span>
{% endif %}
</p>
{% endpartialdef %}
</fieldset>
Each card is now the partial question-card, and the button is the partial add-question. hx-include sends the current TOTAL_FORMS with the request; hx-swap="beforeend" adds the answer at the end of the list. The answer, in a new file, events/templates/events/question_row.html:
events/templates/events/question_row.html
{# What "Add question" gets (Chapter 45): the new card, #}
{# appended to the list; then, out of band, the form #}
{# count, one higher, and the button or the limit. #}
{% if question %}
{% include "events/questions.html#question-card" %}
{% endif %}
<input type="hidden" name="{{ prefix }}-TOTAL_FORMS"
id="id_{{ prefix }}-TOTAL_FORMS" value="{{ total }}"
hx-swap-oob="true">
{% include "events/questions.html#add-question" %}
The new card goes into the list; the hidden total and the button area are swapped out of band. In events/views.py, the imports change in two lines:
events/views.py
from django.http import Http404, HttpResponseBadRequest
events/views.py
require_GET, require_http_methods, require_POST,
In EventUpdateView, replace get_context_data(), and add a view below the class:
events/views.py
def get_context_data(self, **kwargs):
"""Add the title, places taken, and the questions."""
questions = kwargs.setdefault(
'questions', QuestionFormSet(instance=self.object)
)
return super().get_context_data(**kwargs) | {
'title': self.title,
'taken': self.object.places_taken(),
'more_questions': (questions.total_form_count()
< questions.max_num),
}
@require_GET
def question_row(request, event_id):
"""Return one more blank question for the edit page.
Chapter 45. The page sends how many question forms it
has (TOTAL_FORMS); the new one gets the next number,
and the count goes up by one, so the formset reads
every form when the page is saved.
"""
event = event_to_manage(request, event_id,
Action.EDIT_EVENT)
questions = QuestionFormSet(instance=event)
name = f'{questions.prefix}-TOTAL_FORMS'
try:
index = int(request.GET[name])
except (KeyError, ValueError):
return HttpResponseBadRequest('No form count sent.')
index = max(index, 0)
context = {'event': event, 'swapped': True,
'prefix': questions.prefix}
if index < questions.max_num:
form = questions.empty_form
form.prefix = questions.add_prefix(index)
context |= {'question': form, 'total': index + 1}
else:
context['total'] = index
context['more_questions'] = (context['total']
< questions.max_num)
return render(request, 'events/question_row.html',
context)
The formset’s empty_form is Django’s blank form, named with the placeholder __prefix__; giving it the real prefix, questions-1, names its fields correctly. The page sends the count, so the server decides nothing from memory: two quick presses send 1, then 2. event_to_manage() is Chapter 30’s check, so only the event’s organizers get a form, and a refusal is recorded. In events/urls.py, below the edit page:
The button does nothing without JavaScript, so it should not be shown then. At the top of static/otahque/site.js, below its first comment:
static/otahque/site.js
// Chapter 45: controls marked needs-js show only when
// this script runs.
document.documentElement.classList.add('js');
and in static/otahque/source.css, above .form-actions:
static/otahque/source.css
/* Controls that only work with JavaScript, such as Add
question (Chapter 45): site.js marks the page. */
html:not(.js) .needs-js {
display: none;
}
Without JavaScript, the blank form is still there, and saving adds the next one: the plain path is unchanged.
Terminal
npm run build
uv run python manage.py test events.tests.test_question_rows
Output
Found 6 test(s).
Creating test database for alias 'default'...
...
Ran 6 tests in ...s
OK
Step 11: A dialog for Cancel, and the finish
Cancelling a place needs a question first. Since Chapter 31 it has its own page. A dialog on the event page is quicker, and HTML now has one built in: <dialog>. Opened with showModal(), it sits above the page, makes everything behind it unreachable, holds the keyboard inside it, and closes with Escape. Invoker commands, commandfor and command on a button, open and close it with no script at all; they are supported in current versions of the major browsers (Baseline 2025). A browser without them keeps the link to the confirmation page.
A new file, registrations/templates/registrations/cancel_dialog.html:
{# Chapter 45: a link to the confirmation page, or, where #}
{# the browser has invoker commands, a button that opens #}
{# the same question in a dialog. site.js picks one. #}
{% url 'registrations:cancel' place.pk as cancel %}
<p>
<a href="{{ cancel }}" data-fallback>Cancel my place</a>
<button type="button" class="btn btn-outline btn-sm"
commandfor="cancel-place" command="show-modal"
data-invoker hidden>Cancel my place</button>
</p>
<dialog id="cancel-place" class="modal"
aria-labelledby="cancel-title">
<div class="modal-box space-y-4">
<h3 id="cancel-title" class="text-lg font-semibold">
Cancel your place at {{ event.title }}?</h3>
{% if started %}
<p>The event has started, so this place can no longer
be cancelled.</p>
{% else %}
<p>Your place is released for someone else. If
registration has closed, you cannot take it
back.</p>
{% if late %}
<p class="notice-card">The cancellation deadline has
passed, so this counts as a late cancellation.</p>
{% endif %}
{% endif %}
<form method="post" action="{{ cancel }}"
hx-post="{{ cancel }}" class="modal-action"
hx-target="#registration-panel" hx-swap="outerHTML"
hx-disabled-elt="find button">
{% csrf_token %}
<button type="button" class="btn" autofocus
commandfor="cancel-place" command="close">
Keep my place</button>
{% if not started %}
<button type="submit" class="btn btn-error">
{% include "includes/spinner.html" %}
Cancel my place</button>
{% endif %}
</form>
</div>
</dialog>
In registrations/templates/registrations/panel.html, the cancel link:
registrations/templates/registrations/panel.html
<p><a href="{% url 'registrations:cancel' place.pk %}">
Cancel my place</a></p>
becomes:
registrations/templates/registrations/panel.html
{% include "registrations/cancel_dialog.html" %}
The dialog says what the confirmation page says, so registration_panel() in events/views.py gives it the same two facts. From asks = ... to the end of the function:
events/views.py
asks = {'phone_missing', 'answers_needed'}
deadline = event.cancellation_deadline
return {
'place': place,
'reasons': [REASONS[c] for c in codes
if c not in asks],
'needs_details': bool(asks & set(codes)),
'unverified': 'unverified' in codes,
'can_see_attendees': event.can_see_attendees(user),
# For the cancel dialog (Chapter 45).
'started': now >= event.starts_at,
'late': deadline is not None and now >= deadline,
}
Which control to show is the only thing a script decides. At the end of static/otahque/site.js:
static/otahque/site.js
// Where the browser has invoker commands (commandfor),
// show the button that opens a dialog; elsewhere, keep
// the link to the page that asks the same question.
const invokers = 'commandForElement'
in HTMLButtonElement.prototype;
function enhance(root) {
if (!invokers) {
return;
}
for (const button of
root.querySelectorAll('[data-invoker]')) {
button.hidden = false;
}
for (const link of
root.querySelectorAll('[data-fallback]')) {
link.hidden = true;
}
}
enhance(document);
// htmx:load fires for every part htmx puts on the page.
document.addEventListener('htmx:load', (event) => {
enhance(event.detail.elt);
});
With no script, or a browser without invoker commands, the button stays hidden and the link stays. The dialog’s form posts with htmx into the panel; replacing the panel removes the dialog with it.
The finish, in static/otahque/source.css, above .form-actions:
static/otahque/source.css
/* Parts htmx swaps in (Chapter 45) fade in, and the
panel keeps its height, so the page does not jump.
The cancel dialog is a card with a red edge. */
.registration-panel {
min-height: 9rem;
}
.results,
.registration-panel,
.question-card {
transition: opacity 200ms ease-out;
}
.results.htmx-added,
.registration-panel.htmx-added,
.question-card.htmx-added {
opacity: 0;
}
@media (prefers-reduced-motion: reduce) {
.results,
.registration-panel,
.question-card {
transition: none;
}
}
.modal-box {
border: 1px solid var(--color-base-300);
border-top: 6px solid var(--color-error);
}
htmx gives new content the class htmx-added for a moment, so it fades in; the panel keeps a minimum height, so the page below does not jump while its content changes; and a member who asked their system for less motion gets no fade. At the end of PanelSwapTests in registrations/tests/test_panel.py:
npm run build
uv run python manage.py test registrations.tests.test_panel
Output
Found 9 test(s).
Creating test database for alias 'default'...
...
Ran 9 tests in ...s
OK
Step 12: In a browser, the record, and the commit
Run the server and try it: filter the list, page through it, register, cancel through the dialog, add two questions on an edit page, at the width of a phone and of a laptop. Then turn JavaScript off in your browser’s settings and do it all again: every page should work, by whole pages. Figure 45.4 shows the result.
Figure 45.4 — Register in place, and the cancel dialog on a phone.
Record what Otahque serves and how, in a new file, docs/design/htmx.md:
docs/design/htmx.md
# htmx in Otahque
Chapter 45. Every page works without JavaScript; htmx
swaps parts of a page where it runs.
## The file
- htmx 2.0.11, installed with npm (`htmx.org`, exact
version, a development package) and copied to
`static/otahque/htmx-2.0.11.min.js`. Otahque serves it;
no page loads a script from another site.
- SHA-256 of the served file:
`d6fdc75f204e6bdefa99b69bf1e6d4ac`
`69b8a364f77929f45c13476b4000f717`
(one value, split over two lines);
`config/tests/test_htmx_file.py` checks it.
- Settings, in the `htmx-config` meta tag of `base.html`:
no history cache (no copies of pages in the browser),
a full reload when going back, no `eval`, no script
tags in swapped parts, no inline indicator styles.
- htmx 4 is out (August 2026) but npm's default is still
2.x, which the htmx project supports. Revisit when npm's
default or django-htmx's moves to 4, at the latest at
the Django 6.2 upgrade or Chapter 54.
## Rules for a swapped view
- Without `HX-Request`, answer exactly as before.
- With it, return only the part the target names, and
never a redirect: htmx follows it and swaps a whole
page in. Use `HX-Redirect` for a whole-page move.
- A view whose answer depends on the header sends
`Vary: HX-Request`.
- Messages go into the swapped part and the live region
(`#live`), so none is left for the next page.
- A signed-out htmx request gets `HX-Redirect` to sign in
(`accounts.middleware.LoginRequiredMiddleware`).
## What swaps
- The event list: `list.html#results`, by Filter and the
page links.
- The event page: `registrations/panel.html` and
`#places-left`, by Register and Cancel.
- The edit page: one question card and `TOTAL_FORMS`, by
Add question.
Terminal
uv run python check.py
Output
== python manage.py check
System check identified no issues (0 silenced).
== python manage.py makemigrations --check --dry-run
== python manage.py test --parallel
Found 569 test(s).
System check identified no issues (0 silenced).
Ran 569 tests in ...s
OK
== all checks passed
Terminal
git add .
git status --short
git commit -m "Swap parts of pages with htmx"
Output
M accounts/middleware.py
A accounts/tests/test_htmx_sign_in.py
M config/settings.py
A config/tests/test_htmx_file.py
A docs/design/htmx.md
M events/templates/events/facts.html
M events/templates/events/list.html
A events/templates/events/question_row.html
M events/templates/events/questions.html
A events/tests/test_htmx.py
A events/tests/test_question_rows.py
M events/urls.py
M events/views.py
M package-lock.json
M package.json
M pyproject.toml
A registrations/templates/registrations/cancel_dialog.html
M registrations/templates/registrations/panel.html
A registrations/templates/registrations/swapped.html
A registrations/tests/test_csrf.py
A registrations/tests/test_panel.py
M registrations/views.py
A static/otahque/htmx-2.0.11.min.js
M static/otahque/site.css
M static/otahque/site.js
M static/otahque/source.css
M templates/base.html
A templates/includes/spinner.html
M uv.lock
[main 1a2b3c4] Swap parts of pages with htmx
29 files changed, 1104 insertions(+), 24 deletions(-)
create mode 100644 accounts/tests/test_htmx_sign_in.py
create mode 100644 config/tests/test_htmx_file.py
create mode 100644 docs/design/htmx.md
create mode 100644 events/templates/events/question_row.html
create mode 100644 events/tests/test_htmx.py
create mode 100644 events/tests/test_question_rows.py
create mode 100644
registrations/templates/registrations/cancel_dialog.html
create mode 100644
registrations/templates/registrations/swapped.html
create mode 100644 registrations/tests/test_csrf.py
create mode 100644 registrations/tests/test_panel.py
create mode 100644 static/otahque/htmx-2.0.11.min.js
create mode 100644 templates/includes/spinner.html
If something goes wrong
Table 45.3 — Recovery for Chapter 45
What you see
Likely cause
What to do
Nothing happens on Filter or Register
htmx did not load: a wrong path, or the copy step was skipped
Open the browser console; check static/otahque/htmx-2.0.11.min.js exists
A whole page inside the panel
The view redirected, or rendered the whole template, for htmx
Check request.htmx in the view; look at the answer in the Network tab
The spinner always shows
Its rules are in the components layer, before daisyUI's .loading
Keep them in @layer utilities; run npm run build
Forbidden (403) on Register
The form lost its csrf_token, or a non-form request has no header
Keep {% csrf_token %}; keep hx-headers on body
The new question is not saved
TOTAL_FORMS did not go up, or the form was misnumbered
Check the hidden field in the page after Add question
The hash test fails
A different htmx file was copied
Copy it again from node_modules; never edit it
After signing in, Method Not Allowed
next is a POST-only address
Use Otahque's LoginRequiredMiddleware, as in Step 7
Copy it; Get-FileHash or sha256sum; test config.tests.test_htmx_file
d6fdc75f...4000f717; 2 tests OK
request.htmx
seen.py
None False None; true True results
The list
test events.tests.test_htmx
Red first; then 6 tests OK
The panel
test registrations.tests.test_panel
Red first; then 8, and after Step 11, 9 tests OK
Signed out
test accounts.tests.test_htmx_sign_in; test config.tests.test_public
Red first; then 3 OK; Chapter 39's 3 unchanged, OK
CSRF
test registrations.tests.test_csrf
2 tests OK
Add question
test events.tests.test_question_rows
Red first; then 6 tests OK
In a browser
Filter, page links, Register, the dialog, Add question, at 390 and 1280 px; then with JavaScript off
No reload; focus on Registration; whole pages with JavaScript off
All checks
uv run python check.py
== all checks passed; Ran 569 tests
Commit
git log --oneline -1
Swap parts of pages with htmx
Not verified
A screen reader; macOS and Linux shells; browsers other than Edge
Run Narrator or VoiceOver yourself, as in Step 9
The commands were checked in Windows PowerShell 5.1 and Git Bash, from a copy of the Chapter 44 checkpoint with a reader’s data, against PostgreSQL 18; commands that write files ran once, and the copy and hash commands in both shells. The project folder is shortened to ... in printed output. In Microsoft Edge, at 390 and 1280 pixels, a Playwright script pressed Filter, a page link, Register, the dialog’s Cancel, and Add question, and found no page reload, the address bar following the filter and the page, focus on the panel’s heading, “You have a place.” in the live region, the count changed, no message left over, the dialog open and then gone, TOTAL_FORMS one higher, and, with JavaScript off, a plain Register form and no Add question button. One sample event and thirteen short ones were added for those checks and deleted afterwards.
Que. 1 What does progressive enhancement mean for Otahque’s Register button?
Flip to check your answerFold answer back
Answer. It is a form that posts, and works as one with no JavaScript: the view registers and redirects. htmx, where it runs, sends the same form in the background and swaps the panel. The enhancement changes how it feels, never whether it works.
Que. 2 Why does the event list send Vary: HX-Request?
Flip to check your answerFold answer back
Answer. The same address, /events/, answers with a whole page or with the results alone, depending on that header. Vary tells any cache to keep the two apart, so nobody is ever handed the results as if they were the page.
Que. 3 Register used to answer with a redirect. Why not keep that for htmx?
Flip to check your answerFold answer back
Answer. The browser follows redirects before htmx sees them, so htmx would get the whole event page and swap it into the panel, and the message would wait for the next whole page. For htmx the view answers with the panel itself, and uses HX-Redirect when the browser really must load a new page.
Que. 4 How does one answer change both the panel and the places count?
Flip to check your answerFold answer back
Answer. The panel goes where hx-target says. The count comes after it in the same answer, in an element with the same id as the count on the page and hx-swap-oob="true", so htmx replaces that element too: an out-of-band swap.
Que. 5 Sam presses Add question twice. How do the two new forms get different numbers?
Flip to check your answerFold answer back
Answer. The button sends the page’s current TOTAL_FORMS with hx-include. The server numbers the new form with it and swaps in the total one higher, so the second press sends the new total and gets the next number.
Mini-Challenge
When Sai ticks “Only events with places left” and every event is full, the results should say “No events match these filters.” Write a test, in events/tests/test_empty.py, that an htmx request for the results then gets that message, alone, with no page links.
Hint: an event with capacity 1 and one place taken is full. Send places=1, with the headers htmx sends.
Model answer:
events/tests/test_empty.py
"""An empty filter, swapped in (Chapter 45 challenge)."""
from datetime import timedelta
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from django.utils import timezone
from config.helpers import save_event
RESULTS = {'HX-Request': 'true', 'HX-Target': 'results'}
class EmptyResultsTests(TestCase):
"""Only events with places left, when every one is full."""
def test_the_message_is_swapped_in(self):
event = save_event(
starts_at=timezone.now() + timedelta(days=1),
capacity=1)
member = get_user_model().objects.create_user(
'raj@example.org', display_name='Raj')
event.registrations.create(member=member)
part = self.client.get(reverse('events:list'),
{'places': '1'},
headers=RESULTS)
self.assertContains(part,
'No events match these filters.')
self.assertNotContains(part, '<html')
self.assertNotContains(part, 'class="pagination"')
Terminal
uv run python manage.py test events.tests.test_empty
Output
Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...s
OK
The model answer was run and then removed; the chapter’s checkpoint does not include it.
What We Learned
Build the page so it works with HTML alone; add htmx where a reload hurts. The old tests keep checking the plain path.
One view, two answers: the whole template, or a named partial for htmx, chosen by request.htmx, with Vary: HX-Request.
htmx follows redirects silently. Answer htmx with the part itself, and use HX-Redirect for a whole-page move, including signing in.
An out-of-band swap updates a second part of the page from the same answer.
A swap must keep the CSRF token, move focus somewhere sensible, and tell screen readers what changed, through a live region that was already on the page.
Serve your own pinned copy of a script, and record its hash; know which version you chose and what would change that.
Key terms
Use Table 45.5 to explain this chapter’s ideas in your own words.
Table 45.5 — Key terms from Chapter 45
Term
Meaning
Progressive enhancement
Working with HTML alone; better where scripts run.
htmx
A library that sends requests from HTML attributes and swaps in the HTML that comes back.
HX-Request
The header on every htmx request; read as request.htmx.
Partial
A named part of a template, rendered alone as name.html#part.
Out-of-band swap
Replacing a second element, by id, from the same answer.
HX-Redirect
A response header that makes htmx load a whole new page.
Vary
A response header naming the request headers the answer depends on.
Live region
An element whose changes screen readers read out.
Management form
A formset's hidden fields, including TOTAL_FORMS.
Invoker commands
commandfor and command: a button that opens a dialog without script.
SHA-256
A fingerprint of a file; one changed byte changes it.
Readiness checkpoint: you are ready for Chapter 46 when uv run python check.py ends with “all checks passed” and 569 tests, Register and Cancel change only the panel and the count in your browser, the same buttons work with JavaScript off, and git log --oneline -1 shows this chapter’s commit.
Git Commit
Your Chapter 45 work was committed once, in Step 12, as “Swap parts of pages with htmx”: the two packages and the lock files, the served htmx file, the settings and the sign-in middleware, the views, URLs, and templates, site.js and the stylesheet with its compiled CSS, the six test modules, and the design note. If you kept the Mini-Challenge, commit it on its own:
These five questions rehearse the chapter at interview level, from junior to lead. L1 to L3 check what you have just done. L4 and L5 look ahead, to a caching incident and to choosing between htmx and a JavaScript framework. They are extension questions, not a gate to the next chapter. Proof files are run with uv run python manage.py shell -v 0 -c "exec(open('NAME').read())" and deleted afterwards.
L1 (Junior): What is progressive enhancement, in Otahque?
What the interviewer is testing: Can you say what keeps working when the script does not?
Flip to check your answerFold answer back
Perfect answer: Every page is built from forms and links that work by themselves; htmx then makes some of them swap part of a page instead of loading a new one. Without JavaScript, Register posts and redirects, Filter loads the list, and Cancel goes to its page, exactly as before. Table 45.6 sets the two side by side.
Table 45.6 — One action, with and without htmx
Action
Without JavaScript
With htmx
Filter
The whole list page loads
The results swap; the address changes
Register
Redirect; the message on the next page
The panel and count swap; the message read out
Cancel
The confirmation page
A dialog on the event page
Add question
Save, then a new blank form
A new numbered form at once
Behind the scenes:
The same view, two requests
POST /events/7/register/ 302 -> /events/7/
POST /events/7/register/
HX-Request: true 200 panel + count
Code proof: the plain path, still tested:
Output
Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...s
OK
Common mistakes:
Removing method and action from a form because htmx has hx-post.
Calling a page “enhanced” when it does nothing without its script.
Follow-up the interviewer might ask:
How would you know the plain path still works? (Its tests send no htmx headers; and try the page with JavaScript off.)
L2 (Mid-Level): A member’s session ends, and she presses Register
What the interviewer is testing: Can you predict how a redirect meets htmx, and fix it in the right place?
Flip to check your answerFold answer back
Perfect answer: Signed out, Chapter 39’s middleware answers with a redirect to sign in. htmx’s request follows it and gets the sign-in page, which it swaps into the panel, a form inside a form. And next was the Register address, which only answers POST, so after signing in she would see 405. Otahque’s subclass of LoginRequiredMiddleware answers htmx with HX-Redirect, so the browser loads the sign-in page as a page, and sets next to the event page for a POST. One change in the middleware covers every htmx button.
Figure 45.5 — Signed out, with htmx.
Behind the scenes:
Signed out: before and after Step 7
htmx POST 302 /accounts/login/?next=/events/7/register/
htmx POST 200 HX-Redirect: /accounts/login/?next=/events/7/
Code proof: the three signed-out tests:
Output
Found 3 test(s).
Creating test database for alias 'default'...
...
Ran 3 tests in ...s
OK
Common mistakes:
Adding a check to each view instead of the middleware.
Answering htmx with 401 and no instruction, so nothing visible happens.
Follow-up the interviewer might ask:
Why does a GET keep its own address as next? (After signing in, the browser asks with GET, and a GET page can answer it.)
L3 (Senior): Defend serving htmx from Otahque, pinned
What the interviewer is testing: Can you weigh a CDN’s convenience against control?
Flip to check your answerFold answer back
Perfect answer: A script from a CDN runs with the same power as Otahque’s own code, from a server Otahque does not run; an unversioned address can change under you, and a pinned one still needs an integrity hash and a security-policy exception. Serving it ourselves costs about 50 KB in the repository and a deliberate step to upgrade. In return the page loads nothing from another site, works offline in development, and a test fails if the file changes. The version itself was chosen as the line the htmx project supports and npm hands out by default, with a written trigger for moving to 4.
Figure 45.6 — Why the file is pinned and served by Otahque.
Found 2 test(s).
Creating test database for alias 'default'...
...
Ran 2 tests in ...s
OK
Common mistakes:
Pinning in package.json but serving from a CDN anyway.
Editing the vendored file, so it no longer matches its version.
Follow-up the interviewer might ask:
What would you check before moving to htmx 4? (Inheritance, error swaps, history, and the names of events and headers; its upgrade checker; then the browser checks of this chapter.)
L4 (Staff): Members see the results without the page around them
What the interviewer is testing: Can you diagnose a cache serving a partial, looking ahead to Chapter 57’s caching?
Flip to check your answerFold answer back
Perfect answer: Some members, opening /events/ from a bookmark, see only a list of events, unstyled, with no header. That is the results partial served as a whole page. One address gives two answers depending on HX-Request; something between the member and Django, a proxy or a CDN, stored the htmx answer under the address alone and handed it out. The fix is Vary: HX-Request on both answers, which Otahque sends, and checking that every cache in front of the site honours Vary. Chapter 57, on caching, comes back to this when Otahque caches pages.
Figure 45.7 — A partial served as the page.
Behind the scenes:
Cache keys
without Vary /events/ -> one entry
with Vary /events/ + HX-Request -> two entries
Code proof: both answers name the header:
l4_proof.py
"""One address, two answers, and the header that says so."""
from django.test import Client
client = Client(HTTP_HOST='localhost')
for headers in ({}, {'HX-Request': 'true',
'HX-Target': 'results'}):
page = client.get('/events/', headers=headers)
whole = b'<html' in page.content
print(page['Vary'], '| whole page:', whole)
Adding Vary to the htmx answer only: the whole page must say it too.
Using a different address for the partial and forgetting it can be bookmarked.
Follow-up the interviewer might ask:
What else does the list’s answer depend on? (The session’s saved filters and the signed-in member: Vary: Cookie, which Django already adds when the session is read.)
L5 (Lead): htmx, or a JavaScript framework, for Otahque?
What the interviewer is testing: Can you choose an architecture for a team and a product, not for a résumé?
Flip to check your answerFold answer back
Perfect answer: Otahque’s pages are forms and lists over rules the server already enforces: who may register, the event lock, permissions, and the audit trail. htmx keeps all of that in Django and sends HTML, so each enhancement is a few attributes and a partial, and every page still works without the script. A framework such as React would move the page into the browser: an API for every page (Chapter 47 starts one, for other programs, not for these pages), state kept in two places, a build step, and a second language for the team. It is the better choice for an application that lives in the browser, such as a drag-and-drop schedule editor or an offline check-in app. For a community site of forms, htmx gives most of the feel at a fraction of the cost. Revisit if a page needs rich state on the client.
Figure 45.8 — Choosing htmx for Otahque.
Behind the scenes:
What each choice adds
htmx one script, partials, attributes
framework API per page, client state, build, tests x2
Code proof: all the JavaScript Otahque sends:
l5_proof.py
"""How much JavaScript Otahque sends, and who wrote it."""
from pathlib import Path
for name in ('htmx-2.0.11.min.js', 'site.js',
'event-zone.js'):
path = Path('static/otahque') / name
print(f'{name:22} {path.stat().st_size:>7,} bytes')
Choosing by popularity rather than by where the rules live.
Treating htmx as a framework that needs no server design: each swap still needs a view, a partial, and tests.
Follow-up the interviewer might ask:
What would make you add a client-side library later? (A page whose state changes without the server, many times a second, such as a seat picker or an editor.)
Next: Chapter 46, Waitlists, check-in, and registration state transitions, which adds new states to the panel this chapter made swappable: joining a waitlist, being promoted to a place, and showing a check-in code at the door.