Skip to main content

Understanding the code

Before we change anything, let’s take a quick look around the starter project. If you already know Django well, feel free to skim this page.

Code layout

Here are the files that matter for this tutorial:

.
├── manage.py                  # Django's command line tool
├── config/                    # Project-wide settings
│   ├── settings.py
│   └── urls.py                # The top-level URL configuration
└── todo/                      # Our todo app
    ├── models.py              # The TodoItem model (our database table)
    ├── forms.py               # The form for adding new todo items
    ├── urls.py                # The todo app's URLs
    ├── views.py               # The view functions
    ├── templates/todo/
    │   ├── _base.html         # The base page layout. HTMX, Alpine.js and Tailwind are loaded here
    │   ├── home.html          # The main page
    │   └── partials/
    │       └── todo_item.html # A single todo item
    ├── management/commands/   # The add_todos and delete_todos commands
    └── tests/                 # Our tests

Most of our work will happen in views.py, urls.py and the templates.

How Django handles a request

When you open http://127.0.0.1:8000/ in your browser, here’s what happens.

1. A request comes in

Your browser sends a GET request for the path / to the Django development server.

2. The URL is matched

Django looks through the URL patterns to decide which code should handle the request. It starts with config/urls.py:

config/urls.py
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('todo.urls')),
    path('__reload__/', include('django_browser_reload.urls')),
]

The include('todo.urls') line hands everything else over to the todo app’s own URLs:

todo/urls.py
urlpatterns = [
    path('', views.home, name='home'),
]

The path '' matches /, so Django will call views.home. The name='home' part lets us refer to this URL by name elsewhere in the code, instead of hard-coding the path.

3. The view function is called

A view is just a Python function. It takes a request and returns a response:

todo/views.py
def home(request):
    if request.method == "POST":
        form = TodoItemForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect("home")
    else:
        form = TodoItemForm()

    todos = TodoItem.objects.all()
    return render(request, "todo/home.html", {"todos": todos, "form": form})

This view handles two kinds of requests:

  • A GET request, when you first load the page. It shows the todo list and an empty form.
  • A POST request, when you submit the “Add new item” form. It saves the new item, then redirects back to the home page.

4. The view talks to the database using models

We don’t write SQL ourselves. Instead, we describe our data as a model:

todo/models.py
class TodoItem(models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField(blank=True)
    done = models.BooleanField(default=False)

Each TodoItem is a row in a database table. In the view, TodoItem.objects.all() fetches all of them, and form.save() creates a new one.

5. The view renders a template

render takes two important things:

  • A template: an HTML file with some placeholders. Here it’s todo/home.html.
  • A context: a dictionary of values to fill those placeholders with. Here it’s {"todos": todos, "form": form}.
todo/templates/todo/home.html
{% extends "todo/_base.html" %}
{% block body %}
    <h1>Get this done</h1>
    <div class="space-y-3 flex-1 overflow-y-auto pr-2">
        {% for item in todos %}
            {% include "todo/partials/todo_item.html" %}
        {% endfor %}
    </div>
    <h2 class="pt-5">Add new item</h2>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Add</button>
    </form>
{% endblock %}

A few things to notice:

  • {% extends "todo/_base.html" %} means this page is built on top of _base.html, which holds the <head> and loads our scripts.
  • {% for item in todos %} loops over the todos from the context.
  • {% include "todo/partials/todo_item.html" %} renders one todo item. Keeping each item in its own small template (a partial) will be really useful once we start using HTMX.

Here’s that partial:

todo/templates/todo/partials/todo_item.html
<div class="bg-white border border-gray-200 rounded-lg shadow-sm p-4">
    <div class="flex items-center gap-1 mb-1">
        <input type="checkbox" {% if item.done %}checked{% endif %}>
        <p class="font-bold mb-0 {% if item.done %}line-through text-gray-400{% endif %}">{{ item.title }}</p>
    </div>
    <p class="mb-0 {% if item.done %}line-through text-gray-400{% else %} text-gray-600 {% endif %}">{{ item.description }}</p>
</div>

All those class values are Tailwind classes. We’ll look at them on the next page.

6. The response is sent to the browser

The rendered template is plain HTML. Django sends it back to the browser as the response, and the browser displays it.

The big picture

A tall Browser box on the left, and a Django server box on the right. An arrow labelled request goes from Browser into the Django server, to config/urls.py, then on to todo/urls.py, then to views.home. From views.home an arrow points down to TodoItem (database), and from there down to render() with template + context. A final arrow labelled HTML response goes from render() back to the Browser.
Figure 1: A request travels through the URL configs to a view, which gets data from the database and renders a template into the HTML response.

Every feature we build in this tutorial follows this same pattern. HTMX just lets us send these requests without reloading the whole page, and swap the HTML we get back into the right place.