Django next steps: relations and class-based views

We continue the task list from the first Django project. We will sort tasks into categories — your first relation between models — remove extra database queries, rewrite the views with Django's ready-made classes and back it all up with tests. About an hour and a half.

This continues the Django track of the “First project”. Models and migrations are covered in “Databases”.

Rows of card catalogue drawers at the Library of Congress

What you need

We start where the first project ended.

Download the finished code (zip, 9 KB) View on GitHub

  • A completed Django track (steps 1–10). Don't have yours? Download the first project's code and run python manage.py migrate.
  • An active .venv environment with Django 6.1: the command python -m django --version shows the version.
  • A couple of tasks in the database — that way you will see that the old data is still there after the migration.

How to work with the steps. If a block is labelled with a file name, replace the whole file: that way you won't miss an import. The runserver server can keep running the whole time; type commands in a second terminal window. Completed steps are saved in this browser.

Categories, classes and tests

Three parts: a relation between models, class-based views and tests for them.

0 of 9 steps done

  1. Part 1. Relations between models

    Step 1. Describe a category and link tasks to it

    Why a separate model if we could just give a task a text field “category”? We would have to type the text in every task: “Study” and “study” would become different categories, and renaming a category would mean editing every task one by one. A separate table stores each category once, and a task refers to it by its number. This kind of relation is called “many-to-one”: a category has many tasks, a task has one category. In Django it is described by a ForeignKey field.

    tasks/models.py
    from django.db import models
    
    class Category(models.Model):
        name = models.CharField(max_length=50, unique=True)
    
        class Meta:
            ordering = ["name"]
            verbose_name_plural = "categories"
    
        def __str__(self):
            return self.name
    
    class Task(models.Model):
        title = models.CharField(max_length=200)
        done = models.BooleanField(default=False)
        category = models.ForeignKey(
            Category,
            on_delete=models.SET_NULL,
            null=True,
            blank=True,
            related_name="tasks",
        )
    
        def __str__(self):
            return self.title
    tasks/admin.py
    from django.contrib import admin
    
    from .models import Category, Task
    
    admin.site.register(Category)
    
    @admin.register(Task)
    class TaskAdmin(admin.ModelAdmin):
        list_display = ["title", "category", "done"]
        list_filter = ["category", "done"]
    • ForeignKey(Category, …) adds a category_id column — the category number — to the tasks table.
    • on_delete=models.SET_NULL says what to do with tasks when their category is deleted: keep them without a category. CASCADE would delete the tasks together with the category, and PROTECT would forbid deleting a category that still has tasks.
    • null=True allows an empty value in the database: tasks from the first project have no category. blank=True allows the field to be left empty in a form.
    • related_name="tasks" is the name of the reverse relation: every category gets the list of its tasks, category.tasks. It comes in handy in step 3.
    • unique=True prevents two identical categories, and ordering lists categories alphabetically wherever they are shown.
    • TaskAdmin shows the category in the admin's task list and adds filters by category and by the “done” mark.

    Expected result

    The code check passes:

    System check identified no issues (0 silenced).

    The home page, however, if the server is running, now fails with no such column: tasks_task.category_id: the model already knows about the new field, but the database table does not yet. The migration in the next step fixes that.

  2. Step 2. Apply the changes to the database

    makemigrations compares the models with the previous migrations and writes the difference into a new file — a plan of changes. migrate carries out the plan: it creates the categories table and adds a column to the tasks table. Django will not ask any questions: thanks to null=True the old tasks can keep an empty category. Without it makemigrations would ask what to put into the existing rows (see common errors).

    Terminal
    python manage.py makemigrations
    python manage.py migrate

    Expected result

    The first command created a migration file:

    Migrations for 'tasks':
      tasks/migrations/0002_category_task_category.py
        + Create model Category
        + Add field category to task

    The second one applied it:

    Operations to perform:
      Apply all migrations: admin, auth, contenttypes, sessions, tasks
    Running migrations:
      Applying tasks.0002_category_task_category... OK

    The old tasks are still there, they just have no category yet. The home page opens again.

  3. Step 3. Fill in categories and follow the relation both ways

    Open the Django shell and type the lines one at a time. Django 6.1 imports the models into the shell by itself, so you don't need to write import.

    Terminal
    python manage.py shell
    python manage.py shell
    study = Category.objects.create(name="Study")
    home = Category.objects.create(name="Home")
    Task.objects.create(title="Hand in the lab", category=study)
    Task.objects.create(title="Review SQL", category=study)
    Task.objects.create(title="Take out the trash", category=home)
    Category.objects.all()
    study.tasks.all()
    study.tasks.count()
    task = Task.objects.get(title="Take out the trash")
    task.category
    Task.objects.filter(category__name="Study")
    • task.category is the forward relation, from a task to its category.
    • study.tasks is the reverse relation, from a category to its tasks. The name tasks was set by related_name; without it Django would call it task_set.
    • category__name in a filter follows the relation: the double underscore means “go to the category and take its name field”. Django joins the tables in SQL by itself.

    Expected result

    In the shell it looks like this:

    >>> study = Category.objects.create(name="Study")
    >>> home = Category.objects.create(name="Home")
    >>> Task.objects.create(title="Hand in the lab", category=study)
    <Task: Hand in the lab>
    >>> Task.objects.create(title="Review SQL", category=study)
    <Task: Review SQL>
    >>> Task.objects.create(title="Take out the trash", category=home)
    <Task: Take out the trash>
    >>> Category.objects.all()
    <QuerySet [<Category: Home>, <Category: Study>]>
    >>> study.tasks.all()
    <QuerySet [<Task: Hand in the lab>, <Task: Review SQL>]>
    >>> study.tasks.count()
    2
    >>> task = Task.objects.get(title="Take out the trash")
    >>> task.category
    <Category: Home>
    >>> Task.objects.filter(category__name="Study")
    <QuerySet [<Task: Hand in the lab>, <Task: Review SQL>]>

    Before the first >>> line the shell prints the Python version and a line … objects imported automatically — this is Django telling you how many names it imported for you. To leave the shell, type exit().

  4. Step 4. Choose a category in the form and filter the list

    We add the category field to the form: ModelForm turns it into a drop-down list of categories from the database. labels sets Russian field captions — without it Django would show the field names Title and Category. A new category view shows the tasks of one category. Replace all four files.

    tasks/forms.py
    from django import forms
    
    from .models import Task
    
    class TaskForm(forms.ModelForm):
        class Meta:
            model = Task
            fields = ["title", "category"]
            labels = {"title": "Task", "category": "Category"}
    tasks/views.py
    from django.shortcuts import get_object_or_404, redirect, render
    from django.views.decorators.http import require_POST
    
    from .forms import TaskForm
    from .models import Category, Task
    
    def index(request):
        if request.method == "POST":
            form = TaskForm(request.POST)
            if form.is_valid():
                form.save()
                return redirect("index")
        else:
            form = TaskForm()
        return render(request, "tasks/index.html", {
            "tasks": Task.objects.all(),
            "categories": Category.objects.all(),
            "form": form,
        })
    
    def category(request, pk):
        current = get_object_or_404(Category, pk=pk)
        return render(request, "tasks/index.html", {
            "tasks": current.tasks.all(),
            "categories": Category.objects.all(),
            "current": current,
            "form": TaskForm(initial={"category": current}),
        })
    
    @require_POST
    def toggle(request, pk):
        task = get_object_or_404(Task, pk=pk)
        task.done = not task.done
        task.save()
        return redirect("index")
    
    @require_POST
    def delete(request, pk):
        get_object_or_404(Task, pk=pk).delete()
        return redirect("index")
    mysite/urls.py
    from django.contrib import admin
    from django.urls import path
    
    from tasks import views
    
    urlpatterns = [
        path("admin/", admin.site.urls),
        path("", views.index, name="index"),
        path("category/<int:pk>/", views.category, name="category"),
        path("tasks/<int:pk>/toggle/", views.toggle, name="toggle"),
        path("tasks/<int:pk>/delete/", views.delete, name="delete"),
    ]
    tasks/templates/tasks/index.html
    <h1>{% if current %}Tasks: {{ current.name }}{% else %}My tasks{% endif %}</h1>
    
    <nav>
      <a href="{% url 'index' %}">All</a>
      {% for category in categories %}
        · <a href="{% url 'category' category.pk %}">{{ category.name }}</a>
      {% endfor %}
    </nav>
    
    <form method="post" action="{% url 'index' %}">
      {% csrf_token %}
      {{ form.title }}
      {{ form.category }}
      <button>Add</button>
      {{ form.title.errors }}
    </form>
    
    <ul>
      {% for task in tasks %}
        <li>
          {% if task.done %}<s>{{ task.title }}</s>{% else %}{{ task.title }}{% endif %}
          {% if task.category %}<small>{{ task.category.name }}</small>{% endif %}
          <form method="post" action="{% url 'toggle' task.pk %}">
            {% csrf_token %}
            <button>{% if task.done %}Undo{% else %}Done{% endif %}</button>
          </form>
          <form method="post" action="{% url 'delete' task.pk %}">
            {% csrf_token %}
            <button>Delete</button>
          </form>
        </li>
      {% empty %}
        <li>No tasks yet.</li>
      {% endfor %}
    </ul>
    • get_object_or_404 answers with a 404 page if there is no category with that number, instead of a 500 server error.
    • current.tasks.all() is the reverse relation from step 3: only the tasks of this category.
    • initial pre-selects the current category in the form: a task added from the “Study” page goes straight into “Study”.
    • The form is sent to the home page (action="{% url 'index' %}"): the category view only shows the list and does not save.

    Expected result

    Links “All · Home · Study” appear above the form, and a drop-down list next to the field. In the page source (Ctrl + U) it looks like this:

    <select name="category" id="id_category">
      <option value="" selected>- Select an option -</option>
    
      <option value="2">Home</option>
    
      <option value="1">Study</option>
    
    </select>

    The “Home” link leads to /category/2/, where only the task “Take out the trash” is shown. The address /category/999/ answers “Page not found (404)”.

    The empty option “- Select an option -” means “no category”: blank=True allows it. Your category numbers may differ.

  5. Step 5. Remove extra queries: select_related

    The template prints {{ task.category.name }} for every task. Task.objects.all() loads only the tasks, and Django fetches each task's category with a separate query — at the moment the template asks for it. Three tasks mean four queries, a hundred tasks mean a hundred and one. This is called the N+1 problem: the more data, the slower the page. Let's count the queries in the shell:

    python manage.py shell
    from django.db import connection
    from django.test.utils import CaptureQueriesContext
    with CaptureQueriesContext(connection) as queries:
        names = [str(task.category) for task in Task.objects.all()]
    
    len(queries)
    with CaptureQueriesContext(connection) as queries:
        names = [str(task.category) for task in Task.objects.select_related("category")]
    
    len(queries)
    print(queries[0]["sql"])

    select_related("category") joins the two tables in one query (LEFT OUTER JOIN), and the tasks arrive together with their categories. Replace the index function in tasks/views.py: one line changed, "tasks": ….

    tasks/views.py — the index function
    def index(request):
        if request.method == "POST":
            form = TaskForm(request.POST)
            if form.is_valid():
                form.save()
                return redirect("index")
        else:
            form = TaskForm()
        return render(request, "tasks/index.html", {
            "tasks": Task.objects.select_related("category"),
            "categories": Category.objects.all(),
            "form": form,
        })

    The category page does not need this: its tasks come from current.tasks, and Django already knows their category, so there are no extra queries there. For the other side of the relation — for example, listing each category's tasks — there is prefetch_related: it loads everything with a second query.

    Expected result

    Without select_related there are four queries, with it — one:

    >>> from django.db import connection
    >>> from django.test.utils import CaptureQueriesContext
    >>> with CaptureQueriesContext(connection) as queries:
    ...     names = [str(task.category) for task in Task.objects.all()]
    ...
    >>> len(queries)
    4
    >>> with CaptureQueriesContext(connection) as queries:
    ...     names = [str(task.category) for task in Task.objects.select_related("category")]
    ...
    >>> len(queries)
    1
    >>> print(queries[0]["sql"])
    SELECT "tasks_task"."id", "tasks_task"."title", "tasks_task"."done", "tasks_task"."category_id", "tasks_category"."id", "tasks_category"."name" FROM "tasks_task" LEFT OUTER JOIN "tasks_category" ON ("tasks_task"."category_id" = "tasks_category"."id")

    Your number may differ: without select_related it is one query plus one for every task that has a category. Django does not query for the empty category of the old tasks. The empty line after ... is the Enter key that closes the with block.

  6. Part 2. Class-based views

    Step 6. Adding a task — CreateView

    The index function currently does two jobs: it shows the list (GET) and saves the form (POST). For routine work Django has ready-made classes — generic views. Let's start with saving: CreateView creates the form, validates it, saves the task and redirects by itself. All we specify is the model, the form and where to go back to.

    tasks/views.py
    from django.shortcuts import get_object_or_404, redirect, render
    from django.urls import reverse_lazy
    from django.views.decorators.http import require_POST
    from django.views.generic import CreateView
    
    from .forms import TaskForm
    from .models import Category, Task
    
    def index(request):
        return render(request, "tasks/index.html", {
            "tasks": Task.objects.select_related("category"),
            "categories": Category.objects.all(),
            "form": TaskForm(),
        })
    
    def category(request, pk):
        current = get_object_or_404(Category, pk=pk)
        return render(request, "tasks/index.html", {
            "tasks": current.tasks.all(),
            "categories": Category.objects.all(),
            "current": current,
            "form": TaskForm(initial={"category": current}),
        })
    
    class TaskCreateView(CreateView):
        model = Task
        form_class = TaskForm
        success_url = reverse_lazy("index")
    
    @require_POST
    def toggle(request, pk):
        task = get_object_or_404(Task, pk=pk)
        task.done = not task.done
        task.save()
        return redirect("index")
    
    @require_POST
    def delete(request, pk):
        get_object_or_404(Task, pk=pk).delete()
        return redirect("index")
    mysite/urls.py
    from django.contrib import admin
    from django.urls import path
    
    from tasks import views
    
    urlpatterns = [
        path("admin/", admin.site.urls),
        path("", views.index, name="index"),
        path("category/<int:pk>/", views.category, name="category"),
        path("tasks/add/", views.TaskCreateView.as_view(), name="add"),
        path("tasks/<int:pk>/toggle/", views.toggle, name="toggle"),
        path("tasks/<int:pk>/delete/", views.delete, name="delete"),
    ]
    tasks/templates/tasks/index.html
    <h1>{% if current %}Tasks: {{ current.name }}{% else %}My tasks{% endif %}</h1>
    
    <nav>
      <a href="{% url 'index' %}">All</a>
      {% for category in categories %}
        · <a href="{% url 'category' category.pk %}">{{ category.name }}</a>
      {% endfor %}
    </nav>
    
    <form method="post" action="{% url 'add' %}">
      {% csrf_token %}
      {{ form.title }}
      {{ form.category }}
      <button>Add</button>
      {{ form.title.errors }}
    </form>
    
    <ul>
      {% for task in tasks %}
        <li>
          {% if task.done %}<s>{{ task.title }}</s>{% else %}{{ task.title }}{% endif %}
          {% if task.category %}<small>{{ task.category.name }}</small>{% endif %}
          <form method="post" action="{% url 'toggle' task.pk %}">
            {% csrf_token %}
            <button>{% if task.done %}Undo{% else %}Done{% endif %}</button>
          </form>
          <form method="post" action="{% url 'delete' task.pk %}">
            {% csrf_token %}
            <button>Delete</button>
          </form>
        </li>
      {% empty %}
        <li>No tasks yet.</li>
      {% endfor %}
    </ul>
    tasks/templates/tasks/task_form.html
    <h1>New task</h1>
    
    <form method="post">
      {% csrf_token %}
      {{ form.as_p }}
      <button>Add</button>
    </form>
    
    <p><a href="{% url 'index' %}">Back to the list</a></p>
    • The whole if request.method == "POST" branch is gone from index: TaskCreateView now does that job.
    • success_url = reverse_lazy("index") is where to redirect after saving. reverse_lazy works out the address on the first request rather than when the file is loaded: when the class is defined, the routes have not been loaded yet.
    • If the form does not pass validation, CreateView shows a template named after the model — tasks/task_form.html — with the same form and its errors.
    • One line changed in index.html: the form is sent to the new address {% url 'add' %}.

    Expected result

    Tasks are added as before. The server terminal shows that the form goes to the new address and then the browser returns to the home page:

    [17/Nov/2026 07:06:26] "POST /tasks/add/ HTTP/1.1" 302 0
    [17/Nov/2026 07:06:26] "GET / HTTP/1.1" 200 2872

    The browser itself won't send an empty form (the required attribute), but the server checks too. If an empty title does arrive, CreateView returns the “New task” page with an error:

    <ul class="errorlist" id="id_title_error"><li>This field is required.</li></ul>

    The date, the time and the last number — the response size in bytes — will be different for you. The error text is in English because settings.py has LANGUAGE_CODE = 'en-us'; with 'ru' it would read “Обязательное поле.”.

  7. Step 7. The list — ListView

    Now let's replace both index and category with one class. Both pages show the same template; the only difference is which tasks to take. ListView takes the list from the get_queryset() method, so one class serves both routes: on the category page self.kwargs holds the pk from the address.

    tasks/views.py
    from django.shortcuts import get_object_or_404, redirect
    from django.urls import reverse_lazy
    from django.views.decorators.http import require_POST
    from django.views.generic import CreateView, ListView
    
    from .forms import TaskForm
    from .models import Category, Task
    
    class TaskListView(ListView):
        template_name = "tasks/index.html"
        context_object_name = "tasks"
    
        def get_queryset(self):
            self.current = None
            if "pk" in self.kwargs:
                self.current = get_object_or_404(Category, pk=self.kwargs["pk"])
                return self.current.tasks.all()
            return Task.objects.select_related("category")
    
        def get_context_data(self, **kwargs):
            context = super().get_context_data(**kwargs)
            context["categories"] = Category.objects.all()
            context["current"] = self.current
            context["form"] = TaskForm(initial={"category": self.current})
            return context
    
    class TaskCreateView(CreateView):
        model = Task
        form_class = TaskForm
        success_url = reverse_lazy("index")
    
    @require_POST
    def toggle(request, pk):
        task = get_object_or_404(Task, pk=pk)
        task.done = not task.done
        task.save()
        return redirect("index")
    
    @require_POST
    def delete(request, pk):
        get_object_or_404(Task, pk=pk).delete()
        return redirect("index")
    mysite/urls.py
    from django.contrib import admin
    from django.urls import path
    
    from tasks import views
    
    urlpatterns = [
        path("admin/", admin.site.urls),
        path("", views.TaskListView.as_view(), name="index"),
        path("category/<int:pk>/", views.TaskListView.as_view(), name="category"),
        path("tasks/add/", views.TaskCreateView.as_view(), name="add"),
        path("tasks/<int:pk>/toggle/", views.toggle, name="toggle"),
        path("tasks/<int:pk>/delete/", views.delete, name="delete"),
    ]
    • template_name is our template instead of the default tasks/task_list.html. context_object_name = "tasks" is the list's name in the template (the default is object_list), so the template does not need changes.
    • get_queryset() decides which tasks to show: on the home page all of them, with their categories at once; in a category — current.tasks.all().
    • get_context_data() adds what is not part of the list to the template: the categories for the links, the current category and an empty form.
    • toggle and delete stay functions: they need no template or form, and five lines of a function are clearer than a class. Classes pay off where the work is routine.

    Expected result

    System check identified no issues (0 silenced).

    The pages look and work as after step 6, but there is less code. ListView answers only GET: if a form that posts to the home page is left somewhere, the server will answer 405 (see common errors).

  8. Part 3. Tests

    Step 8. Test the views

    Replace the whole tasks/tests.py. TestCase creates a separate empty database for the tests and rolls back the changes after each test, so your tasks are safe. setUpTestData creates the categories and three tasks once for all tests in the class.

    tasks/tests.py
    from django.test import TestCase
    from django.urls import reverse
    
    from .models import Category, Task
    
    class TaskViewsTests(TestCase):
        @classmethod
        def setUpTestData(cls):
            cls.study = Category.objects.create(name="Study")
            cls.home = Category.objects.create(name="Home")
            Task.objects.create(title="Hand in the lab", category=cls.study)
            Task.objects.create(title="Take out the trash", category=cls.home)
            Task.objects.create(title="No category")
    
        def test_list_shows_all_tasks(self):
            response = self.client.get(reverse("index"))
            self.assertEqual(response.status_code, 200)
            self.assertTemplateUsed(response, "tasks/index.html")
            self.assertEqual(len(response.context["tasks"]), 3)
    
        def test_category_shows_only_its_tasks(self):
            response = self.client.get(reverse("category", args=[self.study.pk]))
            self.assertContains(response, "Hand in the lab")
            self.assertNotContains(response, "Take out the trash")
    
        def test_unknown_category_is_404(self):
            response = self.client.get(reverse("category", args=[999]))
            self.assertEqual(response.status_code, 404)
    
        def test_create_saves_task_and_redirects(self):
            response = self.client.post(reverse("add"), {"title": "Water the plants", "category": self.home.pk})
            self.assertRedirects(response, reverse("index"))
            self.assertTrue(self.home.tasks.filter(title="Water the plants").exists())
    
        def test_create_rejects_empty_title(self):
            response = self.client.post(reverse("add"), {"title": ""})
            self.assertEqual(response.status_code, 200)
            self.assertIn("title", response.context["form"].errors)
            self.assertEqual(Task.objects.count(), 3)
    
        def test_list_needs_same_queries_for_any_number_of_tasks(self):
            for number in range(10):
                Task.objects.create(title=f"Task {number}", category=self.study)
            with self.assertNumQueries(3):
                self.client.get(reverse("index"))
    Terminal
    python manage.py test
    • response.context is what the view passed to the template: that is how we see that the home page has exactly three tasks.
    • The filter is checked from both sides: the “Study” task is on the page and the “Home” task is not. A category that doesn't exist answers 404.
    • CreateView saves a task with a category and redirects to the list; an empty title is not saved.
    • assertNumQueries(3) watches for the N+1 problem: the home page makes exactly three queries for any number of tasks — the tasks with their categories, the categories for the links and the categories for the drop-down list.

    Expected result

    Found 6 test(s).
    Creating test database for alias 'default'...
    System check identified no issues (0 silenced).
    ......
    ----------------------------------------------------------------------
    Ran 6 tests in 0.032s
    
    OK
    Destroying test database for alias 'default'...

    The query-count test really does guard select_related. If you change the line in get_queryset to Task.objects.all(), it fails:

    FAIL: test_list_needs_same_queries_for_any_number_of_tasks (tasks.tests.TaskViewsTests.test_list_needs_same_queries_for_any_number_of_tasks)
    AssertionError: 15 != 3 : 15 queries executed, 3 expected
    FAILED (failures=1)

    Your run time will differ. The failure shows 15 queries: the three usual ones plus one for each of the twelve tasks with a category.

  9. Step 9. Check it in the browser

    Start the server and open http://127.0.0.1:8000/. Add a couple of tasks with different categories, follow the category links, mark a task with “Done” and delete another one. The admin at /admin/ now has a Categories section, and the task list has a filter on the right.

    Terminal
    python manage.py runserver

    What it should look like

    The “My tasks” page: links “All · Home · Study”, a field with a drop-down list of categories and four tasks, three of them with a category shown next to them
    The task “Take out the trash” has just been added through the form with the “Home” category, and “Hand in the lab” is marked with “Done”. The old task “Buy bread” has no category.

Test yourself

Answer in your head first, then open the answer.

Why does the ForeignKey have null=True?

The database already held tasks from the first project, and they have no category. null=True allows an empty value in the category_id column, so the migration went through without questions. Without it makemigrations would demand a default value for the old rows.

What happens to the tasks if you delete the “Home” category?

The tasks stay; they just lose their category: that is what on_delete=models.SET_NULL says. The deletion returns (1, {'tasks.Category': 1}) — one category and not a single task deleted. With CASCADE the category's tasks would be deleted too; with PROTECT Django would not let you delete a category that still has tasks.

How is select_related different from prefetch_related?

select_related joins tables in one SQL query (JOIN) and suits the case when each record has one related object: a task has one category. prefetch_related runs a second query and distributes the results among the objects in Python — it is needed for the reverse relation and for many-to-many, for example to show all tasks of each category.

Why, after switching to ListView, does a form posted to the home page get a 405 response?

ListView only answers reading — GET (and the service methods HEAD and OPTIONS). To POST it answers “Method Not Allowed”. Saving now lives in TaskCreateView at /tasks/add/, and that is where the form must be sent.

Why did we set context_object_name = "tasks" in ListView?

By default the list reaches the template as object_list and task_list. Our template from the first project loops over tasks, and one line in the class saves us from editing the template.

Exercise on your own

There are many tasks now — split the list into pages of five tasks with “Previous” and “Next” links. ListView can do this by itself. Don't forget a test: one page holds five tasks, a page that doesn't exist answers 404.

Show the solution

The class gets one line, the template gets page links. ListView passes a page_obj object to the template and answers 404 to a page number that doesn't exist.

tasks/views.py — one new line in TaskListView
class TaskListView(ListView):
    template_name = "tasks/index.html"
    context_object_name = "tasks"
    paginate_by = 5

    # ... get_queryset and get_context_data are unchanged ...
tasks/templates/tasks/index.html — add at the end
{% if page_obj.has_other_pages %}
  <p>
    {% if page_obj.has_previous %}<a href="?page={{ page_obj.previous_page_number }}">Previous</a>{% endif %}
    Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}
    {% if page_obj.has_next %}<a href="?page={{ page_obj.next_page_number }}">Next</a>{% endif %}
  </p>
{% endif %}
tasks/tests.py — a changed test and a new one
    def test_list_needs_same_queries_for_any_number_of_tasks(self):
        for number in range(10):
            Task.objects.create(title=f"Task {number}", category=self.study)
        with self.assertNumQueries(4):
            self.client.get(reverse("index"))

    def test_pagination(self):
        for number in range(10):
            Task.objects.create(title=f"Task {number}")
        first = self.client.get(reverse("index"))
        self.assertEqual(len(first.context["tasks"]), 5)
        self.assertContains(first, "Page 1 of 3")
        self.assertEqual(self.client.get(reverse("index") + "?page=3").status_code, 200)
        self.assertEqual(self.client.get(reverse("index") + "?page=4").status_code, 404)

The paginator counts the tasks with a separate COUNT query, so the query-count test now expects 4, not 3. The other tests pass unchanged: 7 tests in total, OK.

Function or class

Both ways are correct. Classes save code when the work is routine; functions are clearer when the action is unusual.

The same pages in the first project and here
What you need Function (first project) Class (this section)
Show a list render(request, "tasks/index.html", {…}) ListView: get_queryset() and template_name
Save a form if request.method == "POST", is_valid(), save(), redirect() CreateView: model, form_class, success_url
Show form errors pass the form to the template by hand the tasks/task_form.html template with the form
Add data to the template a key in the dictionary for render the get_context_data() method
Suits unusual actions: “Done”, “Delete” routine pages: list, create, update, delete (UpdateView, DeleteView, DetailView)

Common errors and how to fix them

The messages are shown exactly as Django 6.1 prints them. Click an error to see the fix.

«no such column: tasks_task.category_id»

django.db.utils.OperationalError: no such column: tasks_task.category_id The model already knows about the category field, but the database table has no such column yet. Do step 2: python manage.py makemigrations and python manage.py migrate.

makemigrations: «It is impossible to add a non-nullable field 'category'»

It is impossible to add a non-nullable field 'category' to task without specifying a default. This is because the database needs something to populate existing rows. The field has no null=True, and the table already has tasks: the database has nothing to put into their new column. Choose option 2 (Quit and manually define a default value in models.py), add null=True, blank=True to the field as in step 1, and run makemigrations again.

«'Category' object has no attribute 'task_set'»

AttributeError: 'Category' object has no attribute 'task_set' Django gives the reverse relation the name task_set only while the ForeignKey has no related_name. Ours has related_name="tasks", so a category's tasks are category.tasks.all().

“Method Not Allowed (POST): /” and a 405 response

Method Not Allowed (POST): / The add form is sent to the home page, which is now a ListView that accepts only GET. Check the form line in index.html: <form method="post" action="{% url 'add' %}"> (step 6).

«TemplateDoesNotExist: tasks/task_form.html»

django.template.exceptions.TemplateDoesNotExist: tasks/task_form.html CreateView shows this template when the form fails validation or when /tasks/add/ is opened. Create tasks/templates/tasks/task_form.html from step 6 — the name is the model name plus the _form ending.

«Reverse for 'add' not found»

django.urls.exceptions.NoReverseMatch: Reverse for 'add' not found. 'add' is not a valid view function or pattern name. The template refers to the add route, but mysite/urls.py doesn't have it. Add the line path("tasks/add/", views.TaskCreateView.as_view(), name="add").

Test: “AssertionError: 15 != 3 : 15 queries executed, 3 expected”

AssertionError: 15 != 3 : 15 queries executed, 3 expected The home page has the N+1 problem again: select_related("category") disappeared from get_queryset, or the template uses another relation that was not loaded in advance. Bring select_related back as in step 7.

Sources

The code targets Django 6.1. All steps were run on Python 3.13 and Django 6.1.3, sources checked on .

What's next

Publish the project online following the “Deployment” section — after a migration the server needs the same migrate command. And to serve tasks as data rather than a page, have a look at the REST API section.