ContentsClose contents
Pre-release
Chapter 35 · Class-based views and dispatchCHAPTER 35

Complete six-part pre-release for review. No new package and no migration. The event page now answers 405 to methods other than GET and HEAD (a declared change); every other page answers as before. Generic views follow in Chapters 36 and 37.

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 THIRTY-FIVE

Class-based views and dispatch

Stage 5: Growing the application (Chapters 35 to 46)

Prerequisites: Chapters 9 to 34, including the Chapter 34 project with its 362 passing tests and check.py, the view decorators login_required, require_POST, and require_http_methods (Chapters 24 to 31), the refused-access records of Chapter 30, and Python classes at the level of Chapter 4

What you’ll build: Tables of tests that pin how three pages answer every HTTP method, written before anything changes; a hand-made as_view(), compared with Django’s; the event page and the “phone number” page rewritten as class-based views, one with its new answers declared and one with its old answers kept exactly; the event page’s facts in a labelled list with the registration panel as a card; and ADR-006, the house rule that says which of Otahque’s 19 views become classes and which stay functions

Why This Matters

Every one of Otahque’s 19 views is a function, and many of them do the same three things: load an event, check that this person may see it, and answer with a page or a refusal. The next two chapters remove that repetition with Django’s generic views, ready-made views for lists, detail pages, and forms. Sam is keen. Soni, who signed off the first release in Chapter 34, asks one question before anything moves: “If you rewrite the event page, how will we know it still answers exactly as before?”

The obvious answer is “the tests still pass”. This chapter shows why that is not enough. A generic view is a class, and a class-based view answers some requests on its own, before your code runs: a method the page never mentioned, a request for the methods it allows, a header saying which ones it accepts. Rewrite the event page as a class and every one of Otahque’s 362 tests still passes, apart from one that names the old function. Yet the page now answers a PUT request differently, and an attempt that used to be recorded as refused is no longer recorded. Nothing in the suite looks.

So you will write the evidence first. Small tables of tests pin how three pages answer every method, signed in and signed out, and they pass on today’s functions. Then you convert two pages and watch the tables turn red. One change is an improvement you decide to keep and declare. The other is an accident you fix, and the fix is the most important line in the chapter.

By the end of the chapter, you will be able to:

  • explain what a class-based view is, and what as_view(), setup(), and dispatch() do with each request;
  • write tests that pin a page’s answer to every HTTP method before you change it;
  • convert a function view to a View class, keeping its decorators in the order that gives the same answers;
  • recognize when a class changes a page’s answers, and either fix it or declare it;
  • record a house rule that says which views become classes and which stay functions, and why.

Out of scope: generic display views and pagination (Chapter 36), generic editing views and access mixins (Chapter 37), the event’s own registration questions on the converted page (Chapter 38), and sign-in for every page by default (Chapter 39).

PAGE 001

What You Need to Know

Views as classes

New Concept: class-based views

What problem exists? Many views repeat the same shape. Copying that shape into each function means each copy can drift, and a forgotten check in one copy is a security hole (Chapter 30).

What did people do before? Wrote helper functions, such as Otahque’s event_for() and event_to_manage(), and called them from every view.

What is it? A class-based view is a class whose instances answer requests. Instead of one function with if request.method == 'POST': inside it, the class has one method per HTTP method: get() answers GET, post() answers POST. Django’s View class supplies the machinery that picks the right method.

Why use it? Classes can inherit. A generic view such as DetailView already knows how to load one object and render it; you write only what is different. Chapters 36 and 37 rely on that.

Now let’s use it. Steps 4 to 9 build the machinery by hand, read Django’s version, and convert two of Otahque’s pages.

Django does not ask you to choose one style. Its documentation says plainly that class-based views are an alternative to functions, not a replacement, and most real projects mix both. Some experienced developers prefer functions for almost everything, because a function shows every step in one place, while a generic class spreads its steps across several parent classes. Others like classes for the repetitive pages. Both camps are right about something, which is why this chapter ends with a written rule instead of “convert everything”.

The Python you need

A class view uses four Python ideas. The first three are from Chapter 4. A class is a template for objects; each object made from it is an instance. A method is a function defined in a class; Python passes the instance as its first argument, named self, so a method can reach the instance’s attributes. A class can inherit from another and replace some of its methods; super() calls the parent’s version. The fourth may be new: because methods are attributes, Python can find one by its name at run time with the built-in functions getattr() and hasattr(): getattr(page, 'get') returns the get method, and hasattr(page, 'post') says whether there is one. That last idea is the whole trick behind dispatch(). Step 2 runs all four.

HTTP methods and the answers a page can give

Chapter 3 introduced GET (read a page) and POST (send a form). HTTP defines more methods, and anything can send them, not only a browser. A program can send PUT, PATCH, or DELETE to any address; HEAD asks for a page’s headers without its body; OPTIONS asks which methods an address accepts. A page has to answer all of them somehow.

The answer for “this page does not accept that method” is the status 405 Method Not Allowed, and HTTP requires it to carry an Allow header listing the methods the page does accept. Otahque has used 405 since Chapter 26: require_POST answers 405 with Allow: POST to anything but POST. Table 35.1 lists the answers this chapter’s tests name.

Table 35.1 — The answers a method table names
In the table What it means Example
ok 200, or a redirect to somewhere other than sign-in The event page; Register's redirect back to the event
sign in A redirect to the sign-in page login_required, signed out
404 Not found, so a hidden draft reveals nothing A draft's number, for a member who does not organize it
405 GET, POST Method not allowed, with the Allow header require_http_methods(['GET', 'POST'])
recorded A refused-access record was written (Chapter 30) A signed-in member asking for a hidden draft

Under the Hood: why a class answers methods you never wrote

A function view sees every request that reaches its address, whatever the method, and does whatever its code does. Otahque’s event page is a function with no method check at all, so today it answers PUT and DELETE with the full page, exactly as it answers GET. A View class is different. Before your code runs, dispatch() lowers the request’s method name and looks for a method of that name on the instance. If there is none, Django answers 405 itself, and builds the Allow header from the handlers the class does have. Two handlers appear without you writing them: View defines options(), which answers OPTIONS with 200 and the Allow header, and setup() makes head() the same as get() when a class has a get() but no head(). So the moment a page becomes a class, it starts answering three kinds of request differently. Whether that matters is a decision; that it happens is not.

Evidence before change

New Concept: a method table

What problem exists? A refactor, a change to how code is written that should not change what it does, needs proof of “no change”. Otahque’s tests check what each page should do for the methods it was written for. None of them asks what happens to the methods nobody thought about.

What did people do before? Trusted the existing suite, or clicked through the pages by hand.

What is it? A method table is a test whose data is a table: one row per HTTP method, with the answer the page gives signed out and signed in. A small helper sends each request and names the answer in the words of Table 35.1.

Why use it? It is written before the change and passes on the old code, so it records what the page does today. After the change, any row that turns red is a difference, named by method and person.

Now let’s use it. Step 3 writes tables for the event page, the phone page, and Register.

Writing the test first is the habit you have kept since Chapter 9. Here it has a sharper purpose: you cannot argue afterwards about what a page “used to” do if a test wrote it down beforehand.

Two pages to convert, and one to keep

The chapter converts two pages, chosen because they teach different lessons. The event page (event_detail) has one handler, GET, and no decorators: it never chose how to answer other methods, so the class’s answers will be new, and you will decide whether to accept them. The phone page (register_phone, from Chapter 31) asks a member for the phone number an event needs, then registers them. It has two handlers, GET shows the form and POST saves it, and two decorators that chose its answers deliberately: require_http_methods(['GET', 'POST']) outside login_required. Chapter 38 will add each event’s own registration questions to the same page, so as a class it gets a name that covers both: RegistrationDetailsView, the “your details” step of registering.

Register stays a function. It is a one-off action: one method, POST, two decorators, three lines. A class would add answers to OPTIONS and HEAD and an order of decorators to keep, and give nothing back. Its table still pins it, because Chapters 37 and 39 will change how sign-in works, and its rows will show exactly what changes then.

In practice: refactoring a page other programs call

Situation. A page has been live for months. Some clients you do not control, such as a monitoring tool, a browser extension, or a partner’s script, may send it requests you never planned for.

Application. Before rewriting it, a method table records what every method gets today. The refactor then either keeps those answers or changes them on purpose, with a note in the changelog.

Consideration. A table records answers, not reasons. A row that says 200 for DELETE pins a behaviour nobody wanted; the right response is to decide, as Step 7 does, not to preserve it forever.

PAGE 002

How We Build It

Start from Chapter 34, in the folder containing manage.py, with Otahque on PostgreSQL 18, 362 passing tests, check.py, and the work committed (the last commit is “Add the release checklist”, tagged v0.1.0). No package, model, or migration changes. The new files are events/tests/test_methods.py, registrations/tests/test_methods.py, events/templates/events/facts.html, and docs/adr/ADR-006-views.md. config/helpers.py, both apps’ views.py and urls.py, one test in events/tests/test_events.py, three templates, the stylesheet source, and docs/design/permissions.md change. The visible result: the event page shows its time, place, and places as a labelled list, with registration in its own card, and the phone page shows which event you are registering for. The chapter’s commands were checked in Windows PowerShell 5.1 and Git Bash against PostgreSQL 18.

The Custom Way

Before you read how Django turns a class into something a URL can call, build that machinery yourself in a few lines. Step 4 does it, after Step 3 has written the tests. Your version will not be complete, and the gaps are exactly what Django’s version adds.

The Django Way

Step 1: Check the starting point

uv run python manage.py test --parallel
Found 362 test(s).
Creating test database for alias 'default'...
...
Ran 362 tests in ...s

OK
git status --short
git log --oneline -1
... Add the release checklist

Nothing is waiting to be committed, so every change from here on is this chapter’s.

Step 2: A class in Python terms

Create a practice file beside manage.py, practice_class.py. It is plain Python, with no Django:

"""Practice: the class ideas a Django view class needs."""


class Page:
    """A page that answers by method name."""

    greeting = 'Hello'

    def __init__(self, who):
        self.who = who

    def get(self):
        return f'{self.greeting}, {self.who}'


class FriendlyPage(Page):
    """A Page with its own greeting."""

    greeting = 'Welcome'

    def get(self):
        return super().get() + '!'


page = FriendlyPage('Sai')
print(page.get())
print(getattr(page, 'get')())
print(hasattr(page, 'post'))
print(getattr(page, 'post', None))
uv run python practice_class.py
Welcome, Sai!
Welcome, Sai!
False
None

Read the four lines of output against the code. FriendlyPage('Sai') makes an instance; __init__ stores who on it, and every method reaches that through self. FriendlyPage inherits from Page, replaces greeting, and replaces get(), but its get() still calls the parent’s through super(), so the result is the parent’s sentence with the child’s greeting and an exclamation mark. getattr(page, 'get') finds the method from the string 'get', and the () after it calls it. hasattr(page, 'post') is False, and getattr() with a third argument returns that default instead of failing. Delete the file; you have everything dispatch() needs.

Step 3: Pin every answer first

Each table needs a helper that sends one request and names the answer in the words of Table 35.1. It belongs in config/helpers.py, beside outcome(), because both apps’ tables use it. Add two imports there, Client and AuditEvent, so that its Django and project imports read:

from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.test import Client
from django.urls import reverse

from audit.models import AuditEvent
from events.forms import EventForm

Then add two functions at the end of the file:

def answer(client, method, path):
    """Name how a page answered one request, for a table.

    First outcome()'s name ('sign in', 'ok', or the status
    code), then the Allow header if there is one, then
    'recorded' if a refused attempt was recorded.
    """
    refused = AuditEvent.objects.filter(
        outcome=AuditEvent.Outcome.REFUSED
    )
    before = refused.count()
    response = client.generic(method, path)
    words = [outcome(response)]
    if response.has_header('Allow'):
        words.append(response['Allow'])
    if refused.count() > before:
        words.append('recorded')
    return ' '.join(words)


def answers(path, member, method):
    """Return a page's answers signed out and as member."""
    signed_in = Client()
    signed_in.force_login(member)
    return (answer(Client(), method, path),
            answer(signed_in, method, path))

client.generic() sends a request with any method name, which is how the tables reach PUT, TRACE, and the rest. answer() counts refused-access records before and after, so a row can say whether the attempt was recorded. answers() asks twice, once with a fresh client that is signed out and once as the given member, and returns both.

Now the event page’s table. Create events/tests/test_methods.py:

"""How the event page answers every HTTP method.

Written before the page became a class (Chapter 35), so
that any change in its answers fails a test.
"""
from django.contrib.auth import get_user_model
from django.test import TestCase

from config.helpers import answers, save_event
from events.models import Event

User = get_user_model()

# A method, then the answer signed out and the answer
# signed in as a member who organizes nothing.
PUBLISHED = [
    ('GET', 'ok', 'ok'),
    ('HEAD', 'ok', 'ok'),
    ('POST', 'ok', 'ok'),
    ('PUT', 'ok', 'ok'),
    ('PATCH', 'ok', 'ok'),
    ('DELETE', 'ok', 'ok'),
    ('OPTIONS', 'ok', 'ok'),
    ('TRACE', 'ok', 'ok'),
]
HIDDEN = [
    ('GET', '404', '404 recorded'),
    ('HEAD', '404', '404 recorded'),
    ('POST', '404', '404 recorded'),
    ('PUT', '404', '404 recorded'),
    ('OPTIONS', '404', '404 recorded'),
]


class EventPageMethodTests(TestCase):
    """The event page's answer to each method, pinned."""

    @classmethod
    def setUpTestData(cls):
        cls.event = save_event()
        cls.draft = save_event(status=Event.Status.DRAFT)
        cls.sai = User.objects.create_user(
            'sai@example.org', display_name='Sai'
        )

    def check(self, event, table):
        """Compare the page's answers with each row."""
        path = event.get_absolute_url()
        for method, signed_out, signed_in in table:
            with self.subTest(method):
                self.assertEqual(
                    answers(path, self.sai, method),
                    (signed_out, signed_in),
                )

    def test_a_published_event(self):
        self.check(self.event, PUBLISHED)

    def test_a_hidden_draft(self):
        self.check(self.draft, HIDDEN)

Each row is one method. The published event answers ok to everything, because event_detail never looks at the method: that is what the function does today, written down. The hidden draft gives 404 to everyone, and a signed-in member’s attempt is recorded, as Chapter 30 decided. self.subTest(method) reports each failing row separately, by method, instead of stopping at the first.

Create registrations/tests/test_methods.py for the phone page and Register. The phone page’s helpers, soon(), url(), and verified(), belong to the registrations tests, so this file imports them from its neighbour:

"""How Register and the details page answer every method.

Written before the details page became a class (Chapter
35). Register stays a function; its table pins it for the
chapters that change how sign-in works (37 and 39).
"""
from django.test import TestCase

from config.helpers import answers
from events.models import Event

from .test_registrations import soon, url, verified

# A method, then the answer signed out and the answer
# signed in as a member with no phone number yet.
DETAILS = [
    ('GET', 'sign in', 'ok'),
    ('HEAD', '405 GET, POST', '405 GET, POST'),
    ('POST', 'sign in', 'ok'),
    ('PUT', '405 GET, POST', '405 GET, POST'),
    ('PATCH', '405 GET, POST', '405 GET, POST'),
    ('DELETE', '405 GET, POST', '405 GET, POST'),
    ('OPTIONS', '405 GET, POST', '405 GET, POST'),
    ('TRACE', '405 GET, POST', '405 GET, POST'),
]
DETAILS_HIDDEN = [
    ('GET', 'sign in', '404 recorded'),
    ('POST', 'sign in', '404 recorded'),
    ('PUT', '405 GET, POST', '405 GET, POST'),
]
REGISTER = [
    ('GET', '405 POST', '405 POST'),
    ('HEAD', '405 POST', '405 POST'),
    ('POST', 'sign in', 'ok'),
    ('PUT', '405 POST', '405 POST'),
    ('OPTIONS', '405 POST', '405 POST'),
]


class MethodTableTests(TestCase):
    """Each page's answer to each method, pinned."""

    @classmethod
    def setUpTestData(cls):
        cls.event = soon(phone_required=True)
        cls.draft = soon(phone_required=True,
                         status=Event.Status.DRAFT)
        cls.open = soon()
        cls.sai = verified('sai@example.org')

    def check(self, path, table):
        """Compare the page's answers with each row."""
        for method, signed_out, signed_in in table:
            with self.subTest(method):
                self.assertEqual(
                    answers(path, self.sai, method),
                    (signed_out, signed_in),
                )

    def test_the_details_page(self):
        self.check(url('phone', self.event.pk), DETAILS)

    def test_the_details_page_of_a_hidden_draft(self):
        self.check(url('phone', self.draft.pk),
                   DETAILS_HIDDEN)

    def test_register(self):
        self.check(url('register', self.open.pk), REGISTER)

The phone page’s rows show its two decorators at work. require_http_methods is outside, so a wrong method gets 405 with Allow: GET, POST before sign-in is even considered, signed in or not. Then login_required sends a signed-out GET or POST to sign in. Register’s rows show require_POST working the same way. Run both apps’ tests:

uv run python manage.py test events registrations --parallel
Found 262 test(s).
Creating test database for alias 'default'...
...
Ran 262 tests in ...s

OK

All green on the functions, which is the point. The five new tests are a record of today.

Common Error: a table that is green for the wrong reason

If a row is wrong, say you wrote '405 POST' where the page answers '405 GET, POST', the test fails now, before any change, and you correct the row. But a table can also pass while testing nothing, if check() loops over an empty list or the path is wrong for every row. Read each table once against Table 35.1, and break one row on purpose to see it fail.

Step 4: The Custom Way: a hand-made as_view()

A URL pattern needs something it can call with a request, and a class is not that. Write the bridge yourself. Create custom_as_view.py beside manage.py. It is illustration only: it sets Django up so it can make requests, then throws everything away:

"""Practice: a hand-made as_view(), to compare with Django's.

Illustration only: run it once, then delete it.
"""
import os

import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE',
                      'config.settings')
django.setup()

from django.http import (  # noqa: E402
    HttpResponse, HttpResponseNotAllowed,
)
from django.test import RequestFactory  # noqa: E402


def as_view(cls):
    """Return a function that answers with cls's handlers."""
    def view(request, *args, **kwargs):
        instance = cls()
        instance.request = request
        name = request.method.lower()
        handler = getattr(instance, name, None)
        if handler is None:
            allowed = [m.upper() for m in ('get', 'post')
                       if hasattr(instance, m)]
            return HttpResponseNotAllowed(allowed)
        return handler(request, *args, **kwargs)
    view.view_class = cls
    return view


class Hello:
    """A view class with one handler."""

    def get(self, request, name):
        return HttpResponse(f'Hello, {name}')


view = as_view(Hello)
factory = RequestFactory()
for method in ('get', 'post', 'delete'):
    request = getattr(factory, method)('/hello/')
    response = view(request, name='Sai')
    print(method.upper(), response.status_code,
          response.get('Allow', response.content.decode()))
print(view.view_class.__name__)
uv run python custom_as_view.py
GET 200 Hello, Sai
POST 405 GET
DELETE 405 GET
Hello

as_view(Hello) returns a new function, view, that remembers cls (a closure, a function that keeps the variables of the function that made it). Each call makes a fresh instance, so two requests never share self. getattr(instance, name, None) finds get for a GET; there is no post or delete, so those get 405, with an Allow header built from the handlers that exist. view.view_class lets a test ask which class is behind a URL. RequestFactory, from Chapters 10 and 34, builds the requests without a server.

Notice what your version lacks. It answers 405 to OPTIONS and to HEAD. It has no way to pass settings to the class. It checks only get and post. And there is no place to put code that must run before every handler. Delete the file, then read how Django fills each gap.

Step 5: Read Django’s View

Django’s View lives in your virtual environment. Ask Python where:

uv run python -c "import django.views as v; print(v.__file__)"
...\.venv\Lib\site-packages\django\views\__init__.py

Open the folder it names, then generic/base.py inside it, and find class View. Here is the part this chapter uses, from Django 6.1.2, shortened where the ... marks are, and with one line rewrapped to fit the page:

class View:
    http_method_names = [
        "get", "post", "put", "patch",
        "delete", "head", "options", "trace",
    ]

    @classonlymethod
    def as_view(cls, **initkwargs):
        ...
        def view(request, *args, **kwargs):
            self = cls(**initkwargs)
            self.setup(request, *args, **kwargs)
            ...
            return self.dispatch(request, *args, **kwargs)

        view.view_class = cls
        ...
        return view

    def setup(self, request, *args, **kwargs):
        if hasattr(self, "get") and not hasattr(self, "head"):
            self.head = self.get
        self.request = request
        self.args = args
        self.kwargs = kwargs

    def dispatch(self, request, *args, **kwargs):
        method = request.method.lower()
        if method in self.http_method_names:
            handler = getattr(
                self, method, self.http_method_not_allowed
            )
        else:
            handler = self.http_method_not_allowed
        return handler(request, *args, **kwargs)

The shape is yours: as_view() returns a function that makes a new instance for each request and hands the request on. Three things are added. setup() runs first and stores the request and the URL’s values on the instance, so every method can use self.request and self.kwargs; it also makes head the same as get. dispatch() then picks the handler by name, as yours did, but from the full list http_method_names, and calls http_method_not_allowed() for anything missing, which answers 405 with an Allow header listing every name in that list the instance has. And because View itself defines options(), options is always on that list. Figure 35.1 draws the path.

A numbered vertical flow. 1, Request: PUT /events/6/, from a browser or a tool. 2, URLconf: calls the function that as_view() returned. 3, view(): makes a new instance of the class for this request. 4, setup(): keeps request and kwargs, makes head the same as get, and runs before any decorator. Below, a dashed zone labelled “Decorators from method_decorator, in list order” holds step 5, dispatch(), which asks whether the class has a method of that name, and branches to three outcomes: get() or post(), where your code answers; options(), 200 and Allow; and not allowed, 405 and Allow.
Figure 35.1 — From a URL to a handler in a class-based view.

The dashed zone matters in Step 9. Decorators for a class are applied to dispatch(), so they run after setup(), never before it.

Step 6: Convert the event page

Open events/views.py. Change the module’s docstring, since its views will no longer all be functions:

"""The events app's views: a function or a class per page."""

Import View beside the other Django imports:

from django.utils import timezone
from django.views import View
from django.views.decorators.http import (
    require_http_methods, require_POST,
)

from audit.models import AuditEvent, record

Replace the whole event_detail function with a class:

class EventDetailView(View):
    """Show an event its viewer may see, or 404.

    Only get() is written. Django answers HEAD with it,
    answers OPTIONS itself, and refuses any other method
    with 405 (D35.4).
    """

    def get(self, request, event_id):
        """Return the event page, or 404 if it is hidden."""
        event = get_object_or_404(
            Event.objects.with_places(), pk=event_id
        )
        if not event.is_visible_to(request.user):
            deny(request, Action.VIEW_EVENT, event,
                 hidden=True)
        now = timezone.now()
        return render(request, 'events/detail.html', {
            'event': event,
            'now': now,
            'can_edit': event.can_be_edited_by(request.user),
        } | registration_panel(event, request.user, now))

The body of get() is the function’s body, moved one level in; request and event_id arrive as before, because dispatch() passes them on. In events/urls.py, a URL needs the function that as_view() returns, not the class:

    path('events/<int:event_id>/',
         views.EventDetailView.as_view(), name='detail'),

Run both apps’ tests. Do not change any test yet:

uv run python manage.py test events registrations --parallel
Found 262 test(s).
Creating test database for alias 'default'...
ERROR: test_missing_event
AttributeError: module 'events.views' has no attribute
    'event_detail'
FAIL: test_a_hidden_draft [POST]
AssertionError: ('405 GET, HEAD, OPTIONS', '405 GET, HEAD,
    OPTIONS') != ('404', '404 recorded')
FAIL: test_a_hidden_draft [PUT]
AssertionError: ('405 GET, HEAD, OPTIONS', '405 GET, HEAD,
    OPTIONS') != ('404', '404 recorded')
FAIL: test_a_hidden_draft [OPTIONS]
AssertionError: ('ok GET, HEAD, OPTIONS', 'ok GET, HEAD,
    OPTIONS') != ('404', '404 recorded')
... (6 more like these)
Ran 262 tests in ...s

FAILED (failures=9, errors=1)

This is the moment the chapter was built for. The error is the one test the plan once said needed no change: test_missing_event checks that the address resolves to views.event_detail, which no longer exists. The nine failures are the event page’s table. A published event now answers 405 to POST, PUT, PATCH, DELETE, and TRACE, and 200 with an Allow header to OPTIONS. A POST to a hidden draft gets 405 instead of 404, and it is no longer recorded, because the method is refused before get() loads the event. The other 259 tests pass.

Common Error: TypeError: View.__init__() takes 1 positional argument but 2 were given

The URL names the class, views.EventDetailView, instead of views.EventDetailView.as_view(). Django calls whatever the pattern holds with the request, and calling a class makes an instance, which is not a response. Add .as_view().

Step 7: Decide, then declare

The function never chose its answers to PUT or DELETE; it gave the full page to anything. Answering 405 is what HTTP expects, and it is what every generic view in Chapters 36 and 37 will do. So Otahque accepts the class’s answers (decision D35.4). The lost record is acceptable too: a 405 is the same for every event number, existing or not, so the refused method reveals nothing, and the attempt never reaches the event. Declaring a change means the tests say so. In events/tests/test_methods.py, replace the comment and both lists:

# A method, then the answer signed out and the answer
# signed in as a member who organizes nothing. Since
# Chapter 35, Django refuses methods the page does not
# handle, and answers OPTIONS itself (D35.4).
ALLOW = 'GET, HEAD, OPTIONS'
PUBLISHED = [
    ('GET', 'ok', 'ok'),
    ('HEAD', 'ok', 'ok'),
    ('POST', f'405 {ALLOW}', f'405 {ALLOW}'),
    ('PUT', f'405 {ALLOW}', f'405 {ALLOW}'),
    ('PATCH', f'405 {ALLOW}', f'405 {ALLOW}'),
    ('DELETE', f'405 {ALLOW}', f'405 {ALLOW}'),
    ('OPTIONS', f'ok {ALLOW}', f'ok {ALLOW}'),
    ('TRACE', f'405 {ALLOW}', f'405 {ALLOW}'),
]
HIDDEN = [
    ('GET', '404', '404 recorded'),
    ('HEAD', '404', '404 recorded'),
    ('POST', f'405 {ALLOW}', f'405 {ALLOW}'),
    ('PUT', f'405 {ALLOW}', f'405 {ALLOW}'),
    ('OPTIONS', f'ok {ALLOW}', f'ok {ALLOW}'),
]

ALLOW names the header once, so each row stays readable. In events/tests/test_events.py, test_missing_event asks which view answers the address. The function returned by as_view() carries the class as view_class, so ask for that:

        self.assertIs(
            resolve('/events/999/').func.view_class,
            views.EventDetailView,
        )

This is the chapter’s one edit to an existing test, and it says what the test always meant: this address is answered by the event page.

uv run python manage.py test events registrations --parallel
Found 262 test(s).
Creating test database for alias 'default'...
...
Ran 262 tests in ...s

OK

Step 8: The details page, first try

Now the phone page, which becomes RegistrationDetailsView. Its two handlers, GET and POST, look like a perfect fit: get() and post() will declare the methods, so require_http_methods seems unnecessary, and login_required can go on dispatch(). To decorate a method of a class, Django provides method_decorator, which adapts a function decorator to a method; with name='dispatch' it can sit above the class. In registrations/views.py, add two imports:

from django.utils import timezone
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.http import (
    require_http_methods, require_POST,
)

Replace the whole register_phone function with:

@method_decorator(login_required, name='dispatch')
class RegistrationDetailsView(View):
    """Ask for what an event needs, then register.

    Today that is a phone number; Chapter 38 adds the
    event's own questions.
    """

    def dispatch(self, request, *args, **kwargs):
        """Load the event, then call get() or post()."""
        self.event = event_for(request, kwargs['event_id'])
        return super().dispatch(request, *args, **kwargs)

    def get(self, request, event_id):
        """Show the empty form."""
        return self.show(PhoneForm())

    def post(self, request, event_id):
        """Keep the number and take a place, or show errors."""
        form = PhoneForm(request.POST)
        if form.is_valid():
            form.save(request.user)
            return take_place(request, self.event)
        return self.show(form)

    def show(self, form):
        """Render the page with the form."""
        return render(
            self.request, 'registrations/phone.html',
            {'event': self.event, 'form': form},
        )

dispatch() loads the event once, before either handler, so both use self.event, then calls the parent’s dispatch() to pick the handler. show() is an ordinary helper method; Django never calls it. One small difference from the function: PhoneForm(request.POST) is always bound in post(), so a POST with no fields at all shows “This field is required” where the function showed an empty form. A browser always sends the field, so only a hand-made request sees it; the tables cannot, because both answers are 200. In registrations/urls.py:

    path('events/<int:event_id>/register/phone/',
         views.RegistrationDetailsView.as_view(),
         name='phone'),
uv run python manage.py test events registrations --parallel
Found 262 test(s).
Creating test database for alias 'default'...
FAIL: test_the_details_page [HEAD]
AssertionError: ('sign in', 'ok') != ('405 GET, POST', '405
    GET, POST')
FAIL: test_the_details_page [PUT]
AssertionError: ('sign in', '405 GET, POST, HEAD, OPTIONS')
    != ('405 GET, POST', '405 GET, POST')
FAIL: test_the_details_page [PATCH]
AssertionError: ('sign in', '405 GET, POST, HEAD, OPTIONS')
    != ('405 GET, POST', '405 GET, POST')
FAIL: test_the_details_page [DELETE]
AssertionError: ('sign in', '405 GET, POST, HEAD, OPTIONS')
    != ('405 GET, POST', '405 GET, POST')
FAIL: test_the_details_page [OPTIONS]
AssertionError: ('sign in', 'ok GET, POST, HEAD, OPTIONS') !=
    ('405 GET, POST', '405 GET, POST')
... (2 more like these)
Ran 262 tests in ...s

FAILED (failures=7)

Seven rows changed. Signed out, a PUT now goes to sign in instead of 405. Signed in, the Allow header lists four methods instead of two, HEAD gets the form, and OPTIONS gets 200. And a PUT to a hidden draft is now a recorded 404 instead of a 405. Look at the first change closely. In the function, require_http_methods sat outside login_required, so the method was checked first. The class has only login_required around dispatch(), and the method check happens inside dispatch(), after sign-in and after the event is loaded. The order of the checks has turned inside out, as the middle column of Figure 35.2 shows.

Step 9: Keep the function’s order

The fix is to give the class the same decorators as the function, in the same order. method_decorator accepts a list and applies it in list order, the first decorator outermost, exactly as stacked decorators read from the top. Replace the decorator and the docstring above the class:

@method_decorator(
    [require_http_methods(['GET', 'POST']), login_required],
    name='dispatch',
)
class RegistrationDetailsView(View):
    """Ask for what an event needs, then register.

    Today that is a phone number; Chapter 38 adds the
    event's own questions. The list runs in order, as the
    function's decorators did: the method check, sign-in,
    then dispatch() loads the event.
    """
uv run python manage.py test events registrations --parallel
Found 262 test(s).
Creating test database for alias 'default'...
...
Ran 262 tests in ...s

OK

Every row is green again: the class answers exactly as the function did. Figure 35.2 sets the three orders side by side.

Three columns of four numbered cards, each linked by arrows. The function: 1 require_http_methods, PUT gets 405 here; 2 login_required, signed out goes to sign in; 3 event_for(), hidden gives 404, recorded; 4 the page, form or a place. Step 8, first try, marked with a red cross: 1 login_required, every method signs in first, in red; 2 dispatch() loads the event, hidden gives 404, recorded; 3 method check, PUT gets 405 only now, in red; 4 get() or post(). Step 9, the list: the same order as the function, with dispatch() loading the event third.
Figure 35.2 — The function’s order, the first class, and the kept order.

Why keep the old answers here, when Step 7 accepted new ones? Because this page’s answers were chosen. Someone wrote require_http_methods(['GET', 'POST']) above login_required on purpose, in Chapter 31, and a refactor is not the place to undo a decision silently. The event page’s answers were never chosen, so the class’s defaults filled a gap. That distinction becomes rule 2 and rule 3 of ADR-006 in Step 11.

Common Error: loading the object in setup()

setup() looks like the natural place to load the event: it runs before every handler and already stores self.kwargs. But it runs before dispatch(), so before every decorator on dispatch(). Load the event there and a signed-out visitor asking for a hidden draft gets 404 instead of the sign-in page, and a PUT to it gets 404 instead of 405. The table catches it: three rows of the hidden-draft test turn red. Load anything that depends on who is asking in dispatch() or in the handlers. Interview question L4 shows the failing run.

Step 10: The event page’s facts, and a registration card

Chapter 35 touches the event page, so the page improves too. Today it stacks the start, both “Your time” lines, the end, the places, the location, and the organizer as loose lines, then the registration panel below a rule. On a wide screen, half the card is empty. Two changes fix that: the facts become a labelled list, and the registration panel becomes a card beside them on wide screens and below them on phones.

A labelled list in HTML is a description list: <dl> holds pairs of a term, <dt>, and its description, <dd>. Screen readers announce the pairs together, so “Starts” and its time are read as one fact. Create events/templates/events/facts.html, a piece both the event page and the phone page include:

<dl class="facts">
  {% with format="l j F Y, H:i T" %}
  <dt>Starts</dt>
  <dd>{% include "events/when.html" %}</dd>
  <dt>Ends</dt>
  <dd>{% include "events/when.html" with at=event.ends_at %}
  </dd>
  {% endwith %}
  <dt>Where</dt>
  <dd>{{ event.location }}</dd>
  {% if now and now < event.ends_at %}
    {% if event.status != 'cancelled' %}
      <dt>Places</dt>
      <dd>{% include "events/places.html" %}</dd>
    {% endif %}
  {% endif %}
</dl>

The places row appears only when the template has now, the event has not ended, and it is not cancelled, the same conditions as before. The phone page has no now, so it shows time and place only. In events/templates/events/detail.html, replace everything from <h1> down to the panel’s include with:

    <header class="space-y-1">
      <h1>{{ event.title }}</h1>
      {% with names=event.organizer_names %}
        {% if names %}
          <p class="text-sm">
            Organized by {{ names|join:", " }}</p>
        {% endif %}
      {% endwith %}
    </header>
    <div class="grid gap-6 lg:grid-cols-[1fr_20rem]
                lg:items-start">
      <div class="space-y-4">
        {% if event.description %}
          <p>{{ event.description|linebreaksbr }}</p>
        {% endif %}
        {% include "events/facts.html" %}
      </div>
      {% include "registrations/panel.html" %}
    </div>

The organizer’s name moves under the title. lg:grid-cols-[1fr_20rem] is a Tailwind class that gives wide screens two columns, the details and a 20rem card; below Tailwind’s lg width, 64rem, they stack. In registrations/templates/registrations/panel.html, the panel gets a visible heading and a card’s border and background instead of the rule above it. Replace its first two lines with:

<section class="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">
    Registration</h2>

aria-labelledby names the section by its heading, so assistive technology announces “Registration” as before. In registrations/templates/registrations/phone.html, show which event this is, and stop the form stretching across a wide screen. Replace everything from <h1> to the form’s opening tag with:

  <h1>{{ event.title }} asks for a phone number</h1>
  {% include "events/facts.html" %}
  <p>Otahque keeps it on your profile, so you are asked
     only once. You can change it there.</p>
  {% include "registrations/sharing.html" %}
  <form method="post" class="card max-w-xl space-y-4 border
        border-base-300 bg-base-100 p-6">

The shared part is the .facts component. In static/otahque/source.css, inside @layer components, add it just before .form-actions:

  /* Labelled facts, such as an event's time and place
     (Chapter 35): one column on phones, label and value
     side by side from 40rem. */
  .facts {
    display: grid;
    gap: 0.25rem 1.5rem;
  }
  .facts dt {
    padding-top: 0.125rem;
    font-size: 0.875rem;
    font-weight: 600;
  }
  .facts dd {
    margin: 0 0 0.75rem;
  }
  @media (width >= 40rem) {
    .facts {
      grid-template-columns: max-content 1fr;
    }
    .facts dd {
      margin: 0;
    }
  }
  .form-actions {

On a phone, each label sits above its value; from 40rem the labels form a column of their own. Build the stylesheet as in Chapter 14:

npm run build
uv run python manage.py test events registrations --parallel
Found 262 test(s).
Creating test database for alias 'default'...
...
Ran 262 tests in ...s

OK

Run the server and open an event at your browser’s narrowest and widest. Figure 35.3 shows the Online Django clinic, signed in as Sai, before and after.

Three screenshots of the Online Django clinic’s page, signed in as Sai. Top left, before, desktop: the title, the description, then From, Your time, Until, Your time, a places bar, Online, and Organized by Sam as separate lines, with a Register button below a rule, and the right half of the card empty. Bottom left, after, desktop: Organized by Sam under the title; on the left the description and a labelled list, Starts, Ends, Where, and Places, each with its value; on the right a grey card headed Registration with the Register button and the sharing note. Right, after, on a phone: the same labelled list with each label above its value, and the Registration card below it.
Figure 35.3 — The event page before (top) and after (bottom), and after on a phone.

Step 11: Write the house rule

Two pages converted, seventeen to go, or not. Before Chapters 36 and 37 convert more, write down which views become classes, and the rules any conversion follows. Create docs/adr/ADR-006-views.md:

# ADR-006: Function views and class views

## Status

Proposed, November 2026 (Chapter 35). The choices follow
the user's decisions of 24 November 2026 (Chapter 35
D35.1-D35.4); this record is not yet reviewed or accepted.

## Context

For 34 chapters every Otahque view was a function. Many
of them repeat one shape: load an event the viewer may
see, refuse with 404 or 403, render. Django's generic
views (Chapters 36 and 37) remove that repetition, but
they are classes, and a class answers some requests on
its own: HEAD, OPTIONS, and 405 with an Allow header.
Converting a view can change what it answers, and the
existing tests did not notice (Chapter 35, Step 3).

## Options

- A: convert every view to a class.
- B: keep every view a function.
- C: classes where a generic view fits or a page has
  several handlers; small functions for one-off actions.

## Decision

C, with four rules.

1. Before a view is converted, a method table pins its
   answer to every method, signed in and signed out.
2. A conversion keeps every answer the function chose.
   The function's decorators move, in the same order, to
   one method_decorator list on dispatch().
3. Where the function chose nothing, Django's defaults
   are accepted and the table says so (D35.4: the event
   page answers 405 to methods other than GET and HEAD,
   and OPTIONS itself).
4. Nothing that needs sign-in or visibility goes in
   setup(): it runs before the decorators. Load objects
   in dispatch() or in the handlers.

## Inventory (19 views)

Kind now, then where each view goes and why.

events
- home: function, stays (one template, nothing shared).
- event_list: function, ListView in 36.
- EventDetailView: View class since 35; DetailView in 36.
- event_create: function, CreateView in 37.
- event_edit: function, UpdateView in 37.
- event_manage (My events): function, ListView in 36.
- event_publish: function, stays (one-off POST action).
- event_cancel: function, stays (one-off POST action).
- event_delete: function, DeleteView in 37.
- event_copy: function, FormView in 37.
- organizer_events: function, stays until Chapter 67
  makes organizer roles per community.
- event_organizers: function, stays until Chapter 67
  (add-by-email form behind re-authentication).
- remove_organizer: function, stays (one-off POST).

registrations
- register: function, stays (one-off POST action).
- RegistrationDetailsView: View class since 35; gains
  the event's questions in 38.
- my_registrations: function, ListView in 36.
- cancel_registration: function, a class in 37.
- attendees: function, stays until Chapter 41 adds the
  download (a report, not a list of one model).

accounts
- profile: function, FormView in 37 (proposed; not yet
  in Chapter 37's plan).

## Consequences

- Eleven views become classes by Chapter 37; eight stay
  functions, each with a reason above.
- Each converted page's table shows any change in its
  answers, so a change is a decision, not an accident.
- The event page no longer records a refused POST to a
  hidden draft: the method is refused (405) before the
  event is loaded. 405 is the same for every number.
- Chapter 37's LoginRequiredMixin and Chapter 39's
  LoginRequiredMiddleware put sign-in before the method
  check; the tables will show it, and those chapters say
  so.

## Revisit

Chapter 49 (the API), where OPTIONS matters for browsers'
cross-origin checks, and whenever a page in the "stays"
list gains a second handler.

Read the inventory as a plan, not a promise: each line gives the view’s destination and the reason. The “stays” lines are as deliberate as the conversions. Publish, cancel, Register, and remove-organizer are one-off actions with one method each; a class would add answers to keep and nothing to share. Chapter 30’s permissions note also needs the one behaviour that changed on purpose. In docs/design/permissions.md, under “Refusals”, add the last bullet:

- A signed-in refusal is recorded as a refused
  AuditEvent; an unknown number is not.
- Since Chapter 35 the event page refuses any method but
  GET and HEAD with 405 before it loads the event, so a
  POST to a hidden draft is not recorded (ADR-006).

Step 12: Check everything, then commit

uv run python check.py
== python manage.py check
System check identified no issues (0 silenced).
== python manage.py makemigrations --check --dry-run
== python manage.py test --parallel
Found 367 test(s).
System check identified no issues (0 silenced).
Ran 367 tests in ...s
OK
== all checks passed

Three hundred and sixty-two tests, plus five tables. Commit:

git add .
git status --short
git commit -m "Convert the event and details pages to classes"
M  config/helpers.py
A  docs/adr/ADR-006-views.md
M  docs/design/permissions.md
M  events/templates/events/detail.html
A  events/templates/events/facts.html
M  events/tests/test_events.py
A  events/tests/test_methods.py
M  events/urls.py
M  events/views.py
M  registrations/templates/registrations/panel.html
M  registrations/templates/registrations/phone.html
A  registrations/tests/test_methods.py
M  registrations/urls.py
M  registrations/views.py
M  static/otahque/site.css
M  static/otahque/source.css
[main 1a2b3c4] Convert the event and details pages to classes
 16 files changed, 432 insertions(+), 55 deletions(-)
 create mode 100644 docs/adr/ADR-006-views.md
 create mode 100644 events/templates/events/facts.html
 create mode 100644 events/tests/test_methods.py
 create mode 100644 registrations/tests/test_methods.py

When something goes wrong

Table 35.2 — Diagnosing class-based views
Symptom Likely cause Recovery
TypeError: View.__init__() takes 1 positional argument but 2 were given The URL names the class without .as_view() path(..., views.EventDetailView.as_view(), ...)
AttributeError: module 'events.views' has no attribute 'event_detail' A test or URL still names the old function Use .func.view_class in tests; the class in URLs
TypeError: EventDetailView.get() got an unexpected keyword argument 'event_id' The handler's arguments do not match the URL's names def get(self, request, event_id)
Every method gets 405 Handlers named in capitals, such as Get Lower case: get, post
Signed out: sign in, where the table says 405 login_required alone on dispatch(); the method check runs inside dispatch() method_decorator([require_http_methods([...]), login_required], name='dispatch')
Signed out: 404 for a hidden draft, where the table says sign in The object is loaded in setup() Load it in dispatch() or in the handler
A table row fails before any change The row is wrong, not the page Correct the row from what the function does; then change the code
AttributeError: ... has no attribute 'request' setup() was overridden without calling super().setup() Call super().setup(request, *args, **kwargs) first

No recovery here touches your data. The tables run in the test database, and if a conversion goes wrong you can compare it with the committed function: git diff events/views.py shows every change since Chapter 34, and git restore events/views.py puts back the committed file when you would rather start the step again.

PAGE 003

Verify Your Work

Work through Table 35.3 from the folder that holds manage.py.

Table 35.3 — Verification checklist for Chapter 35
Check Command or action Expected result
Starting point test --parallel Found 362 test(s); OK
Python ideas uv run python practice_class.py Welcome, Sai! twice, then False and None
Tables first test events registrations --parallel, after Step 3 Found 262 test(s); OK
The Custom Way uv run python custom_as_view.py GET 200; POST and DELETE 405 with Allow GET
Event page as a class Same tests, after Step 6 FAILED (failures=9, errors=1)
Declared answers Same tests, after Step 7 OK
Details page, first try Same tests, after Step 8 FAILED (failures=7)
Order kept Same tests, after Step 9 OK
UI An event page at 390 and 1280 px Labelled facts; Registration card beside them (wide) or below (phone); no sideways scroll
All checks uv run python check.py == all checks passed; Ran 367 tests
Commit git log --oneline -1 Convert the event and details pages to classes
Not verified macOS and Linux shells; browsers other than Edge Chapter 64 adds CI on Linux for every push

The commands were checked in Windows PowerShell 5.1 and Git Bash, from a copy of the Chapter 34 checkpoint with a reader’s data, against PostgreSQL 18; the project folder is shortened to ... in printed output. The screenshots were taken in Microsoft Edge.

PAGE 004

Checkpoint: Quiz and Challenge

Quiz

Que. 1 What does as_view() return, and why can a URL pattern not use the class itself?

Flip to check your answerFold answer back

Answer. A function. Django calls whatever a pattern holds with the request and the URL’s values, and expects a response back. Calling a class makes an instance instead, so as_view() returns a function that makes an instance for each request, runs setup(), and returns what dispatch() returns.

Que. 2 The event page answered 200 to DELETE as a function and 405 as a class. Where does the 405 come from?

Flip to check your answerFold answer back

Answer. From View.dispatch(). It looks for a method named delete on the instance, finds none, and calls http_method_not_allowed(), which answers 405 with an Allow header built from the handlers the class has: GET, HEAD, OPTIONS.

Que. 3 Why did Step 7 accept the event page’s new answers, but Step 9 refuse the details page’s?

Flip to check your answerFold answer back

Answer. The event page never chose its answers to other methods; the class filled a gap with HTTP’s expected answer. The details page’s answers were chosen in Chapter 31 with require_http_methods above login_required, and a refactor should not undo a decision silently.

Que. 4 method_decorator([require_http_methods(['GET', 'POST']), login_required], name='dispatch'): which check runs first?

Flip to check your answerFold answer back

Answer. The method check. A list is applied in list order, the first outermost, just as stacked decorators read from the top, so a PUT gets 405 before sign-in is considered.

Que. 5 Why should a view not load its event in setup()?

Flip to check your answerFold answer back

Answer. setup() runs before dispatch(), and the decorators wrap dispatch(). Anything in setup() happens before sign-in is checked, so a signed-out visitor can get 404 where the page should send them to sign in.

Mini-Challenge

Chapter 36 will turn My registrations, my_registrations, into a ListView. Following ADR-006 rule 1, pin its answers first, in a new file, registrations/tests/test_mine.py. Predict each row before you run it.

Hint: read the function’s decorators. Which checks does it make, and which does it not?

Model answer: the function has login_required and nothing else, so a signed-out visitor is sent to sign in whatever the method, and a signed-in member gets the page whatever the method:

"""How My registrations answers every method.

Pinned before Chapter 36 makes the page a ListView.
"""
from django.test import TestCase

from config.helpers import answers

from .test_registrations import url, verified

MINE = [
    ('GET', 'sign in', 'ok'),
    ('HEAD', 'sign in', 'ok'),
    ('POST', 'sign in', 'ok'),
    ('PUT', 'sign in', 'ok'),
    ('DELETE', 'sign in', 'ok'),
    ('OPTIONS', 'sign in', 'ok'),
]


class MyRegistrationsMethodTests(TestCase):
    """My registrations' answer to each method, pinned."""

    @classmethod
    def setUpTestData(cls):
        cls.sai = verified('sai@example.org')

    def test_my_registrations(self):
        for method, signed_out, signed_in in MINE:
            with self.subTest(method):
                self.assertEqual(
                    answers(url('mine'), self.sai, method),
                    (signed_out, signed_in),
                )
Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...s

OK

When Chapter 36 converts the page, which rows will change? If login_required stays outermost, the signed-out column stays sign in, and the signed-in rows for POST, PUT, and DELETE become 405 GET, HEAD, OPTIONS. Chapter 36 decides whether to accept that, as Step 7 did. Keep the file; it is the table Chapter 36 starts from.

What We Learned

  • A class-based view answers each HTTP method with a method of the same name; View supplies the machinery.
  • as_view() returns a function; each request gets a new instance; setup() runs, then dispatch() picks the handler or answers 405.
  • A class answers HEAD (with get()), OPTIONS (with options()), and other methods (405 with Allow) before your code runs.
  • A method table pins a page’s answer to every method, signed in and signed out, before any change; the existing suite did not.
  • Where a function chose its answers, keep them: move its decorators, in order, into one method_decorator list on dispatch().
  • Where a function chose nothing, accept Django’s answers on purpose and declare them in the table.
  • Decorators on dispatch() run after setup(); load objects that depend on the visitor in dispatch() or the handlers.
  • A labelled list (<dl>) shows facts as pairs a screen reader keeps together; one shared component serves two pages.
  • ADR-006 records which views become classes and which stay functions, with a reason for each.

Key terms

Use Table 35.4 to explain this chapter’s ideas in your own words.

Table 35.4 — Key terms from Chapter 35
Term Meaning
Class-based view A class whose instances answer requests, one method per HTTP method.
Generic view A ready-made class-based view for a common page, such as a list or a form.
Handler The method that answers one HTTP method, such as get() or post().
as_view() Returns the function a URL pattern calls; it makes an instance per request.
setup() Stores the request and the URL's values on the instance, before dispatch().
dispatch() Picks the handler by the request's method, or answers 405.
405 Method Not Allowed The answer to a method a page does not accept, with an Allow header.
Allow header The list of methods a page accepts.
method_decorator Adapts a function decorator to a method of a class.
Method table A test whose rows pin a page's answer to each method, signed in and out.
Refactor A change to how code is written that should not change what it does.
Description list HTML's dl, dt, and dd: pairs of a term and its description.

Readiness checkpoint: you are ready for Chapter 36 when uv run python check.py ends with “all checks passed” and 367 tests, events/tests/test_methods.py and registrations/tests/test_methods.py pass, the event page shows its facts as a labelled list with a Registration card, docs/adr/ADR-006-views.md lists 19 views, and git log --oneline -1 shows this chapter’s commit.

Git Commit

Your Chapter 35 work was committed once, in Step 12, as “Convert the event and details pages to classes”: the method tables and their helpers, the two classes and their URLs, the one changed test, the facts list and registration card, ADR-006, and the permissions note. If you did the Mini-Challenge, commit registrations/tests/test_mine.py on its own:

git add registrations/tests/test_mine.py
git commit -m "Pin My registrations' answers"
PAGE 005

Test Your Knowledge: Interview Questions

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 debugging a conversion and to setting a rule for a team. 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 does as_view() return, and what happens when a request arrives?

What the interviewer is testing: Do you know the path from a URL to your method?

Flip to check your answerFold answer back

Perfect answer: as_view() is a class method that returns a plain function, and that function is what the URL pattern holds. For each request, the function makes a new instance of the class, calls setup() to store the request and the URL’s values on it, then calls dispatch(). dispatch() lowers the method name and calls the handler of that name, such as get(), or answers 405 with an Allow header if there is none. A new instance per request means two requests never share self. The returned function also carries the class as view_class, so a test can ask which view answers an address.

Table 35.5 — Function view and class view
Question Function view Class view
What the URL holds The function The function as_view() returned
One request One call One new instance
Other methods Whatever the code does 405 with Allow, unless handled
HEAD and OPTIONS Whatever the code does get() for HEAD; options() for OPTIONS

Behind the scenes:

view = Cls.as_view()      once, when urls.py loads
view(request, **kwargs)   each request:
  self = Cls()            new instance
  self.setup(...)         request, args, kwargs
  self.dispatch(...)      handler or 405

Code proof: the event page’s address, resolved:

function view
EventDetailView
['get', 'post', 'put', 'patch', 'delete', 'head', 'options',
    'trace']

Common mistakes:

  • Putting the class in the URL pattern without .as_view().
  • Storing per-request data on the class instead of the instance, where every request would share it.

Follow-up the interviewer might ask:

  • Where would you pass a setting to the class? (As a keyword to as_view(), which accepts only names the class already has, such as template_name.)
  • Why is view_class useful in tests? (It identifies the view without depending on a function’s name.)

L2 (Mid-Level): Predict what a PUT and an OPTIONS get from the event page, before and after

What the interviewer is testing: Can you predict what a class adds before you run anything?

Flip to check your answerFold answer back

Perfect answer: Before, as a function with no method check, both got 200 and the full page; the function did not look at the method. After, EventDetailView has only get(). A PUT finds no put(), so dispatch() calls http_method_not_allowed(): 405, with Allow: GET, HEAD, OPTIONS, because setup() added head and View itself has options. An OPTIONS finds options(): 200, an empty body, and the same Allow header. Otahque accepted both changes on purpose (D35.4) and declared them in the table.

A numbered flow of five cards. 1, a PUT reaches the event page. 2, dispatch(): EventDetailView has no put(). 3, http_method_not_allowed(): 405. 4, Allow: GET, HEAD, OPTIONS, from the handlers it has. 5, the function said 200; D35.4 declares the change.
Figure 35.4 — A PUT to the event page, as a class.

Behind the scenes:

GET, HEAD   get()                 200 or 404
OPTIONS     options()             200, Allow
anything    not allowed           405, Allow

Code proof: three requests to an event, through the test client:

GET 200 -
Method Not Allowed (PUT): /events/1/
PUT 405 GET, HEAD, OPTIONS
OPTIONS 200 GET, HEAD, OPTIONS

The second line is Django’s request log, which records every 405 while DEBUG is on.

Common mistakes:

  • Saying “nothing changes, the tests pass”: the old suite never sent a PUT.
  • Forgetting HEAD and OPTIONS in the Allow header.

Follow-up the interviewer might ask:

  • Would a browser ever send the PUT? (Not from a page; a script or tool can, and must still get a sensible answer.)
  • Does the 405 reveal whether a draft exists? (No: it is the same for every number, existing or not.)

L3 (Senior): Defend keeping Register a function

What the interviewer is testing: Can you resist converting something just because you can?

Flip to check your answerFold answer back

Perfect answer: Register is a one-off action: one method, POST, two decorators, and three lines that hand over to take_place(). A class would share nothing with any other view and has no generic view to inherit from. It would add answers to keep: View brings OPTIONS, and the decorators would need to move, in order, into a method_decorator list to keep 405 before sign-in. That is more code for the same behaviour and a new way to get the order wrong. The house rule keeps classes for pages that a generic view fits or that have several handlers, and Register is neither. Its method table still pins it, so a future change to sign-in, such as Chapter 39’s middleware, shows up as a decision.

A numbered flow of five cards. 1, goal: one action, POST only, signed in. 2, two decorators and three lines today. 3, a class adds OPTIONS, HEAD, and an order to keep. 4, nothing to share: one handler, no generic view. 5, keep the function; revisit if it gains a page.
Figure 35.5 — Why Register stays a function.

Behind the scenes:

POST, signed out    sign in
POST, signed in     a place, then the event page
anything else       405, Allow: POST

Code proof: Register’s table, unchanged since Step 3:

Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...s

OK

Common mistakes:

  • Converting for consistency alone; consistency with a rule that has reasons is the goal, not one style everywhere.
  • Keeping a function but not pinning it, so a later change to sign-in goes unnoticed.

Follow-up the interviewer might ask:

  • When would you convert it? (If it gained a confirmation page, so two handlers, or if a generic view fitted.)
  • What will Chapter 39’s login-by-default middleware change? (Signed out, every method goes to sign in first; the table’s signed-out rows will say so.)

L4 (Staff): After a refactor, a signed-out visitor gets 404 for a hidden draft instead of the sign-in page. Diagnose it

What the interviewer is testing: Can you reason about the order in which a class runs your code?

Flip to check your answerFold answer back

Perfect answer: First, find which rows changed: the method table names the method and the person, so the failure says exactly which answers moved. Here only the hidden draft’s rows changed, and the 404 arrives even for PUT, which should be refused before anything else. Something is loading the event, and refusing, before both decorators. Decorators added with method_decorator(..., name='dispatch') wrap dispatch(), and as_view()’s function calls setup() before dispatch(). So the lookup has been put in setup(). Move it into dispatch(), before super().dispatch(), where it runs after the method check and sign-in, and the rows go green. ADR-006 rule 4 writes this down, because Chapters 36 and 37 will tempt you to load objects early.

A numbered flow of five cards. 1, signed out, a hidden draft: 404, not sign in. 2, the table names the method and the person. 3, setup() runs before the decorators on dispatch(). 4, load the event in dispatch(), after sign-in. 5, rows green; ADR-006 rule 4 says why.
Figure 35.6 — Diagnosing an early lookup.

Behind the scenes:

setup()                      no decorator yet
require_http_methods         405 for PUT
login_required               sign in
dispatch(): event_for()      404, recorded
get() or post()

Code proof: the details page with the event loaded in setup() instead (undone afterwards with git restore):

Found 3 test(s).
Creating test database for alias 'default'...
FAIL: test_the_details_page_of_a_hidden_draft [GET]
AssertionError: ('404', '404 recorded') != ('sign in', '404
    recorded')
FAIL: test_the_details_page_of_a_hidden_draft [POST]
AssertionError: ('404', '404 recorded') != ('sign in', '404
    recorded')
FAIL: test_the_details_page_of_a_hidden_draft [PUT]
AssertionError: ('404', '404 recorded') != ('405 GET, POST',
    '405 GET, POST')
Ran 3 tests in ...s

FAILED (failures=3)

Common mistakes:

  • Adding another login_required inside setup(); the fix is to move the lookup, not to repeat the check.
  • Reading only the status code: the table’s “recorded” also shows which code ran.

Follow-up the interviewer might ask:

  • Is anything safe in setup()? (Work that does not depend on who is asking or reveal anything, such as reading a setting.)
  • How do generic views load objects? (get_object(), called from the handlers, after dispatch(): Chapter 36.)

L5 (Lead): Your team wants to convert every view to a class. Defend the house rule

What the interviewer is testing: Can you set a rule a team can follow, with reasons and a way to revisit it?

Flip to check your answerFold answer back

Perfect answer: The goal is less repetition without behaviour nobody can see. Classes pay off where a generic view fits, such as lists, detail pages, and forms, because the shared code is written once and tested once; and where a page has several handlers. They cost something everywhere: answers the page never chose, a call order spread over parent classes, and decorators that must keep their order. So ADR-006 classifies all 19 views. Eleven become classes in Chapters 35 to 37; eight stay functions, each with a reason: four one-off POST actions, a single-template home page, and three pages waiting for a later chapter. Every conversion starts with a method table, keeps chosen answers, and declares new ones. “Convert everything” trades eight clear functions for consistency; “convert nothing” keeps the repetition that caused Chapter 30’s missed checks. The rule names when to revisit: the API in Chapter 49, and any function that gains a second handler.

A numbered flow of five cards. 1, goal: less repetition, no hidden behaviour. 2, 19 views: 11 fit a generic view or have two handlers. 3, 8 are one-off actions or reports: functions. 4, tables pin the answers before any conversion. 5, revisit at 49, or when a function gains a handler.
Figure 35.7 — The house rule in five steps.

Behind the scenes:

1  tables before any conversion
2  keep chosen answers: decorators in order
3  accept defaults only where nothing was chosen
4  nothing visitor-dependent in setup()

Code proof: the views the URLconf calls today, by kind:

class     EventDetailView
class     RegistrationDetailsView
function  profile
function  home
function  event_list
function  event_create
function  event_manage
function  event_edit
function  event_publish
function  event_cancel
function  event_delete
function  event_copy
function  organizer_events
function  event_organizers
function  remove_organizer
function  register
function  my_registrations
function  cancel_registration
function  attendees
19 views

Common mistakes:

  • A rule without an inventory: “where it fits” means nothing until each view has a destination.
  • Arguing style instead of behaviour; the tables make the argument about answers.

Follow-up the interviewer might ask:

  • What would make you convert attendees? (Chapter 41’s download, if a shared list view would serve both the page and the file.)
  • How do you stop the rule drifting? (The ADR names its revisit points, and a review checks new views against it.)

Next: Chapter 36 turns the event page into a DetailView and the lists into ListViews with pagination, starting from the tables you wrote here.

PAGE 006