Writing the code
Right now, you can tick a checkbox, but nothing gets saved. Refresh the page and the tick is gone.
Goal
- Watch for when the user clicks a checkbox.
- Send a
POSTrequest to the backend. - The backend saves the change to the database.
- No response is needed, because the checkbox already looks checked.
If you get stuck, you can see the finished code for this goal on the 1-check-boxes-should-save-to-db branch.
Installing HTMX
HTMX is already installed. Open todo/templates/todo/_base.html and look inside the <head>:
todo/templates/todo/_base.html
<script src="https://cdn.jsdelivr.net/npm/htmx.org@2.0.11/dist/htmx.min.js"
integrity="sha384-2OatzQy1H+Zd/IIrjr1TcuDGqLXeHhbooAyJY1KdQMKnr4LZ22k31GBLdYKHmVjg"
crossorigin="anonymous"></script>This loads HTMX from a CDN (Content Delivery Network). Every page extends _base.html, so every page gets HTMX.
This is fine for our purposes. In a serious project you would want to install it more carefully, for example by downloading a copy and serving it yourself. See the HTMX installation docs for the options.
1. Add a URL
We’ll need the browser to send a request to the backend. Let’s set up a url for it to point at:
Open todo/urls.py and add a new path:
todo/urls.py
urlpatterns = [
path('', views.home, name='home'),
path('todo/<int:pk>/toggle/', views.toggle_todo_done, name='toggle_todo_done'),
]The <int:pk> part captures a number from the URL and passes it to the view as pk. So a request to /todo/3/toggle/ calls toggle_todo_done(request, pk=3).
The toggle_todo_done view doesn’t exist yet, so if your server is running it will show an error. That’s expected. We’ll write the view next.
2. Add a view
Open todo/views.py. Our new view will need two things we haven’t imported yet. Update the imports at the top of the file:
todo/views.py
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, redirect, renderThen add a new view function at the bottom:
todo/views.py
def toggle_todo_done(request, pk):
todo = get_object_or_404(TodoItem, pk=pk)
todo.done = not todo.done
todo.save()
return HttpResponse()Here’s what it does:
pkis the “primary key” of the todo item: its unique id in the database. It comes from the URL we just added.get_object_or_404fetches the item. If there’s no item with thatpk, Django returns a “404 Not Found” response instead.todo.done = not todo.doneflips the value:TruebecomesFalse, andFalsebecomesTrue.todo.save()writes the change to the database.HttpResponse()sends back an empty response. We don’t need to send anything back yet. We just want the database to be updated.
3. Make the checkbox talk to the server
Now for the HTMX part. Open todo/templates/todo/partials/todo_item.html and add two attributes to the checkbox:
todo/templates/todo/partials/todo_item.html
<input type="checkbox"
{% if item.done %}checked{% endif %}
hx-trigger="click"
hx-post="{% url 'toggle_todo_done' item.pk %}">
hx-trigger="click"tells HTMX to act when the checkbox is clicked.hx-post="..."tells HTMX to send aPOSTrequest to that URL.{% url 'toggle_todo_done' item.pk %}builds the URL for us, using thenamewe gave the path inurls.py. For an item withpk3, it becomes/todo/3/toggle/.
We don’t need hx-target or hx-swap here. The server sends back an empty response, so there’s nothing to put on the page.
If you’re new to Django or Django templates, it helps to see what the browser actually receives. The browser never sees {% url ... %}: Django replaces it with a real URL before sending the page. Refresh the page, open your browser’s developer tools, and use the Elements tab to find one of the checkboxes. Look at its hx-post attribute. You should see something like hx-post="/todo/3/toggle/".
Every modern browser has built-in developer tools. Open them with F12, or right-click the page and choose Inspect. Right-clicking a checkbox and choosing Inspect takes you straight to its HTML.
The Elements tab (called Inspector in Firefox) lets you look at the HTML on the page as it is right now.
The Network tab shows every request the page sends. Click on a request to see exactly what went out and what came back: the URL, the headers, the content, and the status code (like 200 OK or 403 Forbidden).
A common beginner mistake: if you see a 500 error in the Network tab, the problem is not in the frontend. Something crashed on the server. Look at the terminal where Django is running to find the full traceback.
4. Try it out
Make sure the server is running, open http://127.0.0.1:8000/ and click a checkbox.
It doesn’t work! Open your browser’s developer tools and look at the Network tab. You’ll see that the POST request failed with a 403 Forbidden error.
What went wrong: CSRF protection
Django protects every POST request against Cross-Site Request Forgery (CSRF) attacks. It only accepts a POST request if it includes a secret token that Django gave the page.
Our “Add new item” form already does this, with the {% csrf_token %} tag. But the request from our checkbox isn’t coming from a form, so it doesn’t include the token.
The fix: send the token as a header
We can tell HTMX to send the token as a header with every request. Open todo/templates/todo/_base.html and add an hx-headers attribute to the <body> tag:
todo/templates/todo/_base.html
<body class="h-dvh flex flex-col"
hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'>
hx-headers adds extra headers to HTMX requests. Django looks for the token in a header called X-CSRFToken.
HTMX attributes are inherited: elements inside the <body> pick up attributes from the <body>. So by putting hx-headers on the <body>, every HTMX request on every page will include the token. We only have to do this once.
5. Try it again
Refresh the page and click a checkbox. This time, the Network tab shows the request succeeding with a 200 OK.
Now refresh the page. The checkbox stays ticked. 🎉 It was saved to the database.
You might notice something odd though. When you tick an item, it doesn’t get crossed out until you refresh the page. That’s because the crossed-out styling comes from the server, and we’re not re-rendering anything yet. We’ll fix that in the next goal.
What we just did
Here’s the whole journey, from click to database:
- You click the checkbox. Because of
hx-trigger="click", HTMX notices. - Because of
hx-post, HTMX sends aPOSTrequest to/todo/<int:pk>/toggle/, for example/todo/3/toggle/. Thanks tohx-headers, the CSRF token goes with it in a header. - Django looks the URL up in
todo/urls.pyand calls thetoggle_todo_doneview. - The view flips
doneand callstodo.save(), which updates the database. - The view sends back an empty response. HTMX doesn’t do anything with it, so the page doesn’t change.
Recap
- We added a view and a URL that flip a todo item’s
donevalue. - We used
hx-triggerandhx-postto send a request when the checkbox is clicked. - We used
hx-headerson the<body>to send Django’s CSRF token with every HTMX request.