ContentsClose contents
Pre-release
Chapter 39 · Middleware and context processorsCHAPTER 39

Complete six-part pre-release for review. No package and no migration. Eleven signed-out method-table rows change from 405 to the sign-in page (declared).

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-NINE

Middleware and context processors

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

Prerequisites: Chapters 9 to 38, including the Chapter 38 project with its 423 passing tests, the time-zone middleware (Chapter 28), the sign-in checks on each view (Chapters 26, 30, and 37), the refusal records (Chapter 30), the method tables (Chapter 35), and Register’s “busy” answer when the event row stays locked (Chapter 33)

What you’ll build: A request id for every request, sent back in an X-Request-ID header and written into every log line; sign-in required by default, with three pages marked public and a test that lists them; the sign-in checks this makes redundant removed from every view; a context processor that gives every template the site’s name, the support address, and the request’s reference with no database query; and styled 403, 404, and 500 pages and a footer that show that reference

Why This Matters

Sai writes to Otahque’s support address: “Register failed. Screenshot attached.” The screenshot shows a page that says something went wrong, and nothing else. Sam opens the server’s output and finds thousands of lines from that afternoon. Which of them was Sai’s request? Nothing on her screen, and nothing in the log, connects the two.

Sam also has a quieter worry. Every page added since Chapter 26 needed someone to remember login_required or LoginRequiredMixin. In Chapter 30’s practice, one forgotten check was enough to show another organizer’s data. The safe default is the reverse: refuse a signed-out visitor everywhere, and let a page through only when someone has decided it is public, and said so in code.

Both needs have the same shape: something that must happen for every request, whatever the page. Django runs such code in middleware, the layers every request passes through on its way to a view and every response passes through on its way back. A related tool, the context processor, adds values to every template a page renders. This chapter writes one middleware, adopts one that Django provides, writes one context processor, and gives the error pages something useful to say.

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

  • describe the path of a request through the middleware list and back, and why the order matters;
  • write a middleware and test it, with and without the test client;
  • tie log lines to one request with a context variable and a logging filter;
  • make sign-in the default with LoginRequiredMiddleware, and prove which pages are public;
  • write a context processor that costs nothing on every page;
  • replace Django’s plain error pages with your own, including the 500 page, which must not depend on the thing that failed.

Out of scope: structured, searchable logs and how long to keep them (Chapter 65), trusting a request id set by a proxy in front of Otahque (Chapter 63), and asynchronous middleware (Chapter 53).

PAGE 001

What You Need to Know

Middleware

New Concept: middleware

What problem exists? Some work belongs to every request: reading the session, checking the CSRF token, finding the user, choosing the time zone. Writing it in every view would be repetitive, and one forgotten view would break it.

What did people do before? Called the same helper at the top of every view, or wrapped each view in the same decorator, and hoped no one forgot.

What is it? A middleware is a callable that Django builds once at startup, giving it the next handler in the chain, get_response. For each request Django calls the outermost middleware, which may do work, call get_response(request) to pass the request inward, and do more work on the response that comes back. MIDDLEWARE in settings.py lists them from the outside in.

Why use it? Code in middleware runs for every request without any view asking for it, including requests for pages that do not exist yet.

Now let’s use it. Step 2 prints Otahque’s list; Step 3 builds a chain by hand; Step 4 writes one.

Otahque’s list after this chapter is in Figure 39.1. A request goes down the list, reaches the view, and the response goes back up in the reverse order. A middleware may also answer without calling get_response() at all, as LoginRequiredMiddleware does when it sends a visitor to sign in: then the view and every middleware below it never see the request.

Six numbered cards in a column joined by downward arrows. 1, RequestIDMiddleware: request.id is a new UUID4; the id is set for log records. 2, Security, Session, Common, CSRF: Django’s HTTPS rules, the session, slashes, the token. 3, AuthenticationMiddleware: request.user, from the session. 4, LoginRequiredMiddleware, in red: a visitor, and the view is not marked public: sign in. 5, Time zone, messages, clickjacking, allauth. 6, the view: checks permissions, reads the database, renders the page. An arrow from the view runs up the right side, labelled response, back up, to a card To the browser, with X-Request-ID, added by step 1 on the way out.
Figure 39.1 — A request through Otahque’s middleware, and its response back.

Order matters because each middleware may depend on what an earlier one did. AuthenticationMiddleware reads the session, so it comes after SessionMiddleware; LoginRequiredMiddleware reads request.user, so it comes after AuthenticationMiddleware. Django checks that last rule itself when it starts.

A request’s reference

To find Sai’s request, the page she sees and the log line Sam reads must carry the same value. Otahque gives each request a request id, a random UUID made when the request arrives, and puts it in three places: on the request (request.id), in a response header (X-Request-ID), and in every log line written while the request is handled. The pages show it too, as a “reference” a member can copy. Figure 39.3, in Step 9, follows one reference from Sai’s screen to Sam’s log.

The log line is the tricky part. A log call such as log.warning('register busy') does not receive the request. Python’s context variables solve this: a ContextVar holds one value per thread, and per task in asynchronous code, so the middleware can set it at the start of a request and a logging filter can read it when any log line is written. The middleware resets it afterwards, so no id leaks into the next request handled by the same thread.

Under the Hood: why the id is always new

Many systems accept a request id that arrives in the request’s own X-Request-ID header, so one id can follow a request through several servers. But anyone can send that header. A visitor who sends X-Request-ID: 1f3a..., the id of another member’s request, could make their own lines look like that member’s in the log. Until Otahque runs behind a proxy it controls (Chapter 63), the middleware ignores any id it is sent and makes a new one.

Sign-in by default

Django 5.1 added LoginRequiredMiddleware. For every request it looks at the view the URL resolved to: if the visitor is not signed in and the view is not marked with the login_not_required decorator, it redirects to the sign-in page, with ?next= set to the page they asked for. Marking is the only way out. There is no list of public addresses in settings, on purpose: a page is public because its view says so, next to its code.

This is the deny by default rule from security guidance such as OWASP’s: refuse unless something explicitly allows. Figure 39.2 shows the result for Otahque. Three of Otahque’s pages are public: the home page, the event list, and the event page. allauth already marks its own pages, such as sign-in, sign-up, and password reset. Everything else asks a visitor to sign in first, including any page someone adds tomorrow and forgets to think about.

Two groups. Left, Public, login_not_required: Home, Event list, Event page, allauth’s sign-in pages. Right, Everything else, sign in first: Register, Details, My registrations, New event, Edit, copy, delete, Attendee list, Profile, Organizer access. Below, a wide card: a new view starts on the right; it is public only when someone marks it, and a test lists exactly the public pages.
Figure 39.2 — Deny by default: the public pages, and everything else.

In practice: sign-in is not permission

Situation. With the middleware in place, a reader is tempted to delete every check from the views.

Application. The middleware answers one question: is this person signed in? It cannot answer “may Raj edit Sam’s event?”, because it never loads the event. ManageEventMixin, PermissionRequiredMixin, and deny() stay exactly where they are; only the sign-in checks become redundant.

Consideration. Interview question L5 asks you to defend this split.

Context processors

New Concept: context processors

What problem exists? The footer on every page needs the support address and the request’s reference. Adding them to the context in every view would repeat the same lines in thirty places.

What did people do before? Exactly that, or a base view class every view had to inherit.

What is it? A context processor is a function that takes the request and returns a dictionary. Django calls every processor listed in TEMPLATES whenever a template is rendered with the request, such as by render() or a class-based view, and adds the dictionaries to the context. startproject listed three of Django’s in Otahque’s settings, and the pages have used them without saying so: request, auth, which gives the navigation its user and perms, and messages.

Why use it? One function supplies values to every page.

Now let’s use it. Step 8 writes site() for the footer.

The cost is the other side of “every page”. A query in a context processor runs on every page, including pages that never show its result, and including error pages. Otahque’s site() therefore reads only settings and the request, and a test proves it runs no query at all.

Error pages

When a view raises Http404 or PermissionDenied, Django renders 404.html or 403.html if the project has them, with the request, so context processors run. With DEBUG on, a 404 shows Django’s yellow debugging page instead, so you see Otahque’s pages only with DEBUG off, as in tests and on a real server.

The 500 page is different. It appears when something failed, and the failure may be the database, the session, or a template. So Django renders 500.html with an empty context and no context processors, and a project that wants to show more must write its own handler and name it in the root URL configuration as handler500. Otahque’s handler passes exactly three values, none of which needs the database.

PAGE 002

How We Build It

Start from Chapter 38, in the folder containing manage.py, with Otahque on PostgreSQL 18, 423 passing tests, and the work committed (the last commit is “Ask each event’s own questions”). No package and no migration is new. The new files are config/middleware.py, config/context_processors.py, config/views.py, four test modules in config/tests/, the templates problem.html, 403.html, 404.html, 500.html, and includes/site_footer.html. config/settings.py, config/urls.py, .env.example, templates/base.html, the stylesheet source, the views of all three apps, one method table, and four design notes change. The visible result: every page ends with a footer naming the support address and the page’s reference; a missing or refused page explains itself and shows the reference; and a signed-out visitor who opens any page other than the home page, the event list, or an event page is asked to sign in. The chapter’s commands were checked in Windows PowerShell 5.1 and Git Bash against PostgreSQL 18.

The Custom Way

A middleware chain sounds like framework magic. It is a few functions, each holding the next. Step 3 builds a chain of two by hand, with no Django at all, and shows the order in which they run.

The Django Way

Step 1: Check the starting point

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

OK
git status --short
git log --oneline -1
... Ask each event's own questions

Step 2: Read the middleware list

Create practice_list.py beside manage.py:

"""Practice: print the middleware list, in order.

Run it once, then delete it.
"""
import os

import django

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

from django.conf import settings  # noqa: E402

for number, name in enumerate(settings.MIDDLEWARE, 1):
    print(number, name)
uv run python practice_list.py
1 django.middleware.security.SecurityMiddleware
2 django.contrib.sessions.middleware.SessionMiddleware
3 django.middleware.common.CommonMiddleware
4 django.middleware.csrf.CsrfViewMiddleware
5 django.contrib.auth.middleware.AuthenticationMiddleware
6 accounts.middleware.TimezoneMiddleware
7 django.contrib.messages.middleware.MessageMiddleware
8 django.middleware.clickjacking.XFrameOptionsMiddleware
9 allauth.account.middleware.AccountMiddleware

Delete practice_list.py. Seven of the nine come from Django. Number 6 is Otahque’s own time-zone middleware from Chapter 28, and number 9 is allauth’s. Read the list as layers from the outside in: SecurityMiddleware sees every request first and every response last.

Step 3: Build a chain by hand (the Custom Way)

Create practice_chain.py. It contains no Django: a “view” that returns a string, and a function that makes middleware which print their names.

"""Practice: two middleware by hand, with no Django.

A middleware is a callable that is given the next
handler and returns a handler. Run it, then delete it.
"""


def view(request):
    """Answer the request: the innermost handler."""
    print('  view handles', request)
    return 'page'


def make_middleware(name):
    """Return a middleware factory that prints its name."""
    def middleware(get_response):
        def handler(request):
            print('in ', name)
            response = get_response(request)
            print('out', name)
            return response
        return handler
    return middleware


# Like MIDDLEWARE = [outer, inner]: wrap from the inside.
handler = view
for factory in reversed([make_middleware('outer'),
                         make_middleware('inner')]):
    handler = factory(handler)

print('result:', handler('/events/'))
uv run python practice_chain.py
in  outer
in  inner
  view handles /events/
out inner
out outer
result: page

outer runs first on the way in and last on the way out, because it wraps inner, which wraps the view. Django builds its chain the same way at startup, wrapping from the end of MIDDLEWARE back to the start. Delete practice_chain.py.

Step 4: A request id, test-first

The tests, in a new file config/tests/test_request_id.py, say what the middleware must do: a new 32-character id in the header of every response, never the one a browser sends, the same id inside the view and in a log line written there, and nothing left behind afterwards.

"""Each request's id, in its header and logs (Chapter 39)."""
import logging

from django.http import HttpResponse
from django.test import RequestFactory, TestCase
from django.urls import reverse

from config.middleware import (
    RequestIDFilter, RequestIDMiddleware, current_id,
)

log = logging.getLogger('otahque.tests')


def seen_by_view(request):
    """Report the id this view sees, and log one line."""
    log.warning('inside the view')
    return HttpResponse(current_id.get())


class RequestIDTests(TestCase):
    """Every request gets its own id, in header and logs."""

    def test_the_header_holds_a_new_id_each_time(self):
        first = self.client.get(reverse('events:list'))
        second = self.client.get(reverse('events:list'))
        self.assertEqual(len(first['X-Request-ID']), 32)
        self.assertNotEqual(first['X-Request-ID'],
                            second['X-Request-ID'])

    def test_an_id_sent_by_the_browser_is_not_used(self):
        page = self.client.get(reverse('events:list'),
                               headers={'X-Request-ID': 'x1'})
        self.assertNotEqual(page['X-Request-ID'], 'x1')

    def test_the_view_and_the_log_see_the_same_id(self):
        middleware = RequestIDMiddleware(seen_by_view)
        log.addFilter(RequestIDFilter())
        self.addCleanup(log.filters.clear)
        with self.assertLogs('otahque.tests') as logs:
            response = middleware(RequestFactory().get('/'))
        reference = response['X-Request-ID']
        self.assertEqual(response.content.decode(), reference)
        self.assertEqual(logs.records[0].request_id, reference)

    def test_no_id_is_left_behind(self):
        with self.assertLogs('otahque.tests'):
            RequestIDMiddleware(seen_by_view)(
                RequestFactory().get('/')
            )
        self.assertEqual(current_id.get(), '-')
uv run python manage.py test config.tests.test_request_id
Found 1 test(s).
Creating test database for alias 'default'...
ERROR: test_request_id
ImportError: Failed to import test module: test_request_id
Ran 1 test in ...s

FAILED (errors=1)

Red, because config/middleware.py does not exist. Create it:

"""Middleware for the whole project (Chapter 39)."""
import logging
import uuid
from contextvars import ContextVar

# The id of the request being handled, read by log records.
current_id = ContextVar('request_id', default='-')


class RequestIDMiddleware:
    """Give each request an id, for its page and its logs.

    The id goes on the request, into the X-Request-ID
    header, and into log records. It is always new: an id
    a browser sends is not trusted until our own proxy
    sets it (Chapter 63).
    """

    def __init__(self, get_response):
        """Keep the next handler in the chain."""
        self.get_response = get_response

    def __call__(self, request):
        """Set the id, call the rest, then add the header."""
        request.id = uuid.uuid4().hex
        token = current_id.set(request.id)
        try:
            response = self.get_response(request)
        finally:
            current_id.reset(token)
        response['X-Request-ID'] = request.id
        return response


class RequestIDFilter(logging.Filter):
    """Add request_id to each log record a handler sees."""

    def filter(self, record):
        """Copy the current id onto the record; keep it."""
        record.request_id = current_id.get()
        return True

__init__() runs once, when Django builds the chain; __call__() runs for every request. The try and finally reset the context variable even if something below raises. RequestIDFilter is used in Step 5. In config/settings.py, add the middleware at the top of the list:

MIDDLEWARE = [
    # First, so every response and log line has an id.
    'config.middleware.RequestIDMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'accounts.middleware.TimezoneMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'allauth.account.middleware.AccountMiddleware',
]
uv run python manage.py test config.tests.test_request_id
Found 4 test(s).
Creating test database for alias 'default'...
...
Ran 4 tests in ...s

OK

First in the list means first to see the request and last to touch the response, so every response gets the header, even a redirect another middleware makes without reaching a view.

Step 5: Put the id in the logs

Django’s logging is configured with one dictionary, LOGGING. Add it at the end of config/settings.py:

# Logging (Chapter 39): each line names its request's id.
# Otahque's own warnings, and errors from Django's request
# handling, such as a 500, go to the console.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'request_id': {
            '()': 'config.middleware.RequestIDFilter',
        },
    },
    'formatters': {
        'plain': {
            'format': '{levelname} [{request_id}] {name}: '
                      '{message}',
            'style': '{',
        },
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'filters': ['request_id'],
            'formatter': 'plain',
        },
    },
    'loggers': {
        # Warnings and above, the level loggers inherit.
        'otahque': {
            'handlers': ['console'],
        },
        'django.request': {
            'handlers': ['console'],
            'level': 'ERROR',
            'propagate': False,
        },
    },
}

A filter may change or drop a record; request_id adds the id to every record the console handler sees, and the formatter prints it in square brackets. Two loggers use the handler: Otahque’s own, otahque and every logger named below it, such as otahque.registrations, and Django’s django.request, which records each 500 with its traceback. propagate: False stops a 500 being printed twice, once here and once by Django’s own django logger.

Now Register can say something worth searching for. When the event row stays locked too long, Chapter 33’s register() refuses with “busy”, and the member sees “Otahque is busy. Please try again.” That is exactly the moment someone writes to support. In registrations/views.py, add import logging as the first import, and below Action = AuditEvent.Action add log = logging.getLogger('otahque.registrations'). Then take_place() becomes:

def take_place(request, event, answers=None):
    """Register the member, then say what happened.

    If the event still needs a phone number or answers,
    the member is sent to the details page.
    """
    try:
        event.register(request.user, timezone.now(), answers)
    except ValidationError as error:
        codes = [e.code for e in error.error_list]
        if set(codes) <= {'phone_missing', 'answers_needed'}:
            return redirect('registrations:details',
                            event.pk)
        if codes == ['already_registered']:
            messages.info(request, REASONS['already_registered'])
        else:
            if 'busy' in codes:
                # The member will ask what went wrong: one
                # line, with this request's id (Chapter 39).
                log.warning('register busy: event %s',
                            event.pk)
            for message in error.messages:
                messages.error(request, message)
    else:
        messages.success(request, 'You have a place.')
    return redirect(event)

The line is a warning because it describes a problem Otahque had, not one the member caused. A test of the full path, from a failing page to the log line, comes in Step 9.

Common Error: a log level that hides what a test expects

Setting 'level': 'INFO' on the otahque logger looks harmless, but a logger’s level also filters what it passes to its parents. Chapter 29’s test that no log holds a password listens at the root logger with assertLogs(level='DEBUG') and expects Otahque’s debug line; with INFO on otahque the line never arrives and the test fails with “no logs of level DEBUG or higher triggered on root”. Leave the level unset: the logger then inherits the root’s level, warnings and above by default, and tests may lower it.

Step 6: Sign-in by default

First the test of what must be true afterwards, in config/tests/test_public.py: Otahque’s own pages that are public are exactly three, a visitor is sent to sign in from every other one, and the public ones open.

"""Sign-in by default, and the pages that are public.

Chapter 39: LoginRequiredMiddleware sends a visitor to
sign in unless the view is marked login_not_required.
"""
from importlib import import_module

from django.test import TestCase
from django.urls import reverse

# The pages anyone may open, signed in or not.
PUBLIC = {'events:home', 'events:list', 'events:detail'}


def own_pages():
    """Yield each page of Otahque's apps: name, route, view."""
    for app in ('accounts', 'events', 'registrations'):
        urls = import_module(f'{app}.urls')
        for pattern in urls.urlpatterns:
            yield (f'{app}:{pattern.name}', str(pattern.pattern),
                   pattern.callback)


class LoginByDefaultTests(TestCase):
    """Every page needs sign-in unless it is listed public."""

    def test_exactly_these_pages_are_public(self):
        public = {name for name, _, view in own_pages()
                  if not getattr(view, 'login_required', True)}
        self.assertEqual(public, PUBLIC)

    def test_a_visitor_is_sent_to_sign_in_elsewhere(self):
        sign_in = reverse('account_login')
        for name, route, _ in own_pages():
            if name in PUBLIC:
                continue
            args = [1] * route.count('<int:')
            with self.subTest(name):
                address = reverse(name, args=args)
                page = self.client.get(address)
                self.assertRedirects(
                    page, f'{sign_in}?next={address}',
                    fetch_redirect_response=False,
                )

    def test_public_pages_open_signed_out(self):
        for name in ('events:home', 'events:list'):
            with self.subTest(name):
                page = self.client.get(reverse(name))
                self.assertEqual(page.status_code, 200)

own_pages() walks each app’s urlpatterns. A view’s login_required attribute is what the middleware reads; login_not_required sets it to False, and an unmarked view has none, which counts as True.

uv run python manage.py test config.tests.test_public
Found 3 test(s).
Creating test database for alias 'default'...
FAIL: test_a_visitor_is_sent_to_sign_in_elsewhere
AssertionError: 405 != 302 : Response didn't redirect as
    expected: Response code was 405 (expected 302)
FAIL: test_a_visitor_is_sent_to_sign_in_elsewhere
AssertionError: 405 != 302 : Response didn't redirect as
    expected: Response code was 405 (expected 302)
FAIL: test_a_visitor_is_sent_to_sign_in_elsewhere
AssertionError: 405 != 302 : Response didn't redirect as
    expected: Response code was 405 (expected 302)
FAIL: test_a_visitor_is_sent_to_sign_in_elsewhere
AssertionError: 405 != 302 : Response didn't redirect as
    expected: Response code was 405 (expected 302)
FAIL: test_exactly_these_pages_are_public
AssertionError: Items in the second set but not the first:
Ran 3 tests in ...s

FAILED (failures=5)

Five failures. test_exactly_these_pages_are_public fails because no page is marked public yet. The other four are the pages that accept only POST: publish, cancel, remove an organizer, and Register. Their require_POST answers a visitor’s GET with 405 before login_required is asked, so the visitor is never sent to sign in. The middleware will answer before either. Add the middleware in config/settings.py, right after AuthenticationMiddleware; the whole list is now:

MIDDLEWARE = [
    # First, so every response and log line has an id.
    'config.middleware.RequestIDMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    # Every page needs sign-in unless its view is marked
    # login_not_required (Chapter 39).
    'django.contrib.auth.middleware.LoginRequiredMiddleware',
    'accounts.middleware.TimezoneMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'allauth.account.middleware.AccountMiddleware',
]

and run the whole suite:

uv run python manage.py test --parallel
Found 430 test(s).
Creating test database for alias 'default'...
ERROR: test_each_page [1]
IndexError: list index out of range
ERROR: test_each_page [2]
IndexError: list index out of range
ERROR: test_each_page [3]
IndexError: list index out of range
ERROR: test_each_page [last]
IndexError: list index out of range
... (99 more like these)
Ran 430 tests in ...s

FAILED (failures=98, errors=5)

Every test that opens the home page, the event list, or an event page signed out now lands on the sign-in page instead. Mark the three views in events/views.py. At the top, the decorators import becomes:

from django.contrib.auth.decorators import (
    login_not_required, login_required,
)

and below from django.utils import timezone add from django.utils.decorators import method_decorator. Then mark home() and the two classes:

@login_not_required
def home(request):
    """Welcome visitors to Otahque."""
    return render(request, 'events/home.html')


@method_decorator(login_not_required, name='dispatch')
class EventListView(ListView):
    ...


@method_decorator(login_not_required, name='dispatch')
class EventDetailView(DetailView):
    ...

login_not_required works on a function. A class-based view is a class until as_view() turns it into a function, so the attribute must reach that function: as_view() copies the attributes of dispatch() onto it, which is why the decorator goes on dispatch through method_decorator.

uv run python manage.py test --parallel
Found 430 test(s).
Creating test database for alias 'default'...
FAIL: test_register [GET]
AssertionError: ('sign in', '405 POST') != ('405 POST', '405
    POST')
FAIL: test_register [HEAD]
AssertionError: ('sign in', '405 POST') != ('405 POST', '405
    POST')
FAIL: test_register [PUT]
AssertionError: ('sign in', '405 POST') != ('405 POST', '405
    POST')
FAIL: test_register [OPTIONS]
AssertionError: ('sign in', '405 POST') != ('405 POST', '405
    POST')
FAIL: test_the_details_page [HEAD]
AssertionError: ('sign in', '405 GET, POST') != ('405 GET,
    POST', '405 GET, POST')
FAIL: test_the_details_page [PUT]
AssertionError: ('sign in', '405 GET, POST') != ('405 GET,
    POST', '405 GET, POST')
FAIL: test_the_details_page [PATCH]
AssertionError: ('sign in', '405 GET, POST') != ('405 GET,
    POST', '405 GET, POST')
FAIL: test_the_details_page [DELETE]
AssertionError: ('sign in', '405 GET, POST') != ('405 GET,
    POST', '405 GET, POST')
FAIL: test_the_details_page [OPTIONS]
AssertionError: ('sign in', '405 GET, POST') != ('405 GET,
    POST', '405 GET, POST')
FAIL: test_the_details_page [TRACE]
AssertionError: ('sign in', '405 GET, POST') != ('405 GET,
    POST', '405 GET, POST')
FAIL: test_the_details_page_of_a_hidden_draft [PUT]
AssertionError: ('sign in', '405 GET, POST') != ('405 GET,
    POST', '405 GET, POST')
Ran 430 tests in ...s

FAILED (failures=11)

Eleven rows of Chapter 35’s method tables fail, all signed out. Before, Register’s require_POST answered a visitor’s GET with 405 before login_required was asked; the middleware now answers first, with the sign-in page. The same is true of the details page’s methods other than GET and POST. The answers are right, so the tables change, on purpose. In registrations/tests/test_methods.py:

# A method, then the answer signed out and the answer
# signed in as a member with no phone number yet. Since
# Chapter 39 the middleware answers a visitor first:
# sign in, whatever the method.
DETAILS = [
    ('GET', 'sign in', 'ok'),
    ('HEAD', 'sign in', '405 GET, POST'),
    ('POST', 'sign in', 'ok'),
    ('PUT', 'sign in', '405 GET, POST'),
    ('PATCH', 'sign in', '405 GET, POST'),
    ('DELETE', 'sign in', '405 GET, POST'),
    ('OPTIONS', 'sign in', '405 GET, POST'),
    ('TRACE', 'sign in', '405 GET, POST'),
]
DETAILS_HIDDEN = [
    ('GET', 'sign in', '404 recorded'),
    ('POST', 'sign in', '404 recorded'),
    ('PUT', 'sign in', '405 GET, POST'),
]
REGISTER = [
    ('GET', 'sign in', '405 POST'),
    ('HEAD', 'sign in', '405 POST'),
    ('POST', 'sign in', 'ok'),
    ('PUT', 'sign in', '405 POST'),
    ('OPTIONS', 'sign in', '405 POST'),
]
uv run python manage.py test --parallel
Found 430 test(s).
Creating test database for alias 'default'...
...
Ran 430 tests in ...s

OK

Common Error: login_not_required on the class

Writing @login_not_required directly above class EventListView raises no error, and the page still redirects visitors to sign in: the attribute lands on the class, which the middleware never sees. Put it on dispatch() with method_decorator, as above, and let test_exactly_these_pages_are_public catch the mistake.

Step 7: Remove the checks the middleware has made redundant

Every sign-in check in the views now runs after the middleware has already made the same check. They do no harm, but each one suggests to a reader that sign-in is that view’s job, and a later chapter might copy the pattern into a page that is meant to be public. Table 39.1 lists the removals; permission checks stay.

Table 39.1 — Sign-in checks removed in Step 7
File Change
events/views.py `login_required` leaves the decorators import; `LoginRequiredMixin` leaves the mixins import; `@login_required` goes from `event_publish`, `event_cancel`, `organizer_events`, `event_organizers`, and `remove_organizer`; `LoginRequiredMixin, ` goes from `EventCreateView`, `EventUpdateView`, `EventDeleteView`, and `EventCopyView`
registrations/views.py Both sign-in imports go; `@login_required` goes from `register`; the details page's decorator list becomes `require_http_methods(['GET', 'POST'])` alone; `LoginRequiredMixin, ` goes from `MyRegistrationsView`, `CancelRegistrationView`, `AnswersView`, and `AttendeesView`
accounts/views.py The import goes; `ProfileView(FormView)`

Two methods were written to let visitors through to the old mixin, and become simpler. EventCreateView:

class EventCreateView(CreateView):
    """Create an event, for members who may add events.

    The middleware has sent visitors to sign in; dispatch()
    refuses a member without add_event, recorded.
    """

    form_class = EventForm
    template_name = 'events/form.html'
    http_method_names = ['get', 'post']

    def dispatch(self, request, *args, **kwargs):
        """Refuse members who may not add events."""
        if not request.user.has_perm('events.add_event'):
            deny(request, Action.CREATE_EVENT)
        return super().dispatch(request, *args, **kwargs)

and the start of AnswersView.dispatch():

    def dispatch(self, request, *args, **kwargs):
        """Refuse another member's place, or after the start."""
        self.place = own_place(request,
                               kwargs['registration_id'],
                               Action.CHANGE_ANSWERS)

The decorators import in events/views.py is now:

from django.contrib.auth.decorators import (
    login_not_required,
)
from django.contrib.auth.mixins import PermissionRequiredMixin

The docstrings of ManageEventMixin, MyEventsView, and RegistrationDetailsView mention the old order; change them to name the middleware. Then:

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

OK

The same 430 tests, unchanged, pass: the method tables already describe the middleware’s answers.

Step 8: The site’s values on every page

Write the test first, in config/tests/test_site_values.py:

"""Values every template may use, and the footer (Chapter 39)."""
from django.test import RequestFactory, TestCase
from django.urls import reverse

from config.context_processors import site


class SiteValuesTests(TestCase):
    """site() reads settings and the request: no queries."""

    def test_no_queries(self):
        request = RequestFactory().get('/')
        request.id = 'abc123'
        with self.assertNumQueries(0):
            values = site(request)
        self.assertEqual(values['request_id'], 'abc123')
        self.assertEqual(values['site_name'], 'Otahque')

    def test_every_page_has_the_footer(self):
        page = self.client.get(reverse('events:list'))
        self.assertContains(page, 'Need help?')
        self.assertContains(page, page['X-Request-ID'])

Then the context processor, in a new file config/context_processors.py:

"""Values every template may use (Chapter 39).

A context processor runs for every page, so these read
settings and the request only: no database queries.
"""
from django.conf import settings


def site(request):
    """Return the site's name, support address, request id."""
    return {
        'site_name': settings.SITE_NAME,
        'support_email': settings.SUPPORT_EMAIL,
        'request_id': getattr(request, 'id', ''),
    }

Register it in config/settings.py; the list in TEMPLATES becomes:

                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                (
                    'django.contrib.messages.'
                    'context_processors.messages'
                ),
                'config.context_processors.site',

and below LOGIN_URL add the two settings it reads:

# Shown on every page's footer and on error pages.
SITE_NAME = 'Otahque'
SUPPORT_EMAIL = config('DJANGO_SUPPORT_EMAIL',
                       default='support@otahque.example')

.env.example gains, below DJANGO_ADMIN_URL:

# The address shown in the footer and on error pages.
DJANGO_SUPPORT_EMAIL=support@otahque.example

The footer, in a new file templates/includes/site_footer.html:

{# On every page (Chapter 39): who to ask for help, and #}
{# the reference that finds this page's request in logs. #}
<footer class="site-footer">
  <p>Need help? Write to
    <a href="mailto:{{ support_email }}">
      {{ support_email }}</a>.</p>
  {% if request_id %}
    <p>Reference <code>{{ request_id }}</code></p>
  {% endif %}
</footer>

In templates/base.html, include it after </main>: {% include "includes/site_footer.html" %}.

uv run python manage.py test config.tests.test_site_values
Found 2 test(s).
Creating test database for alias 'default'...
...
Ran 2 tests in ...s

OK

Common Error: a context processor that is never called

If the footer shows “Write to .” with nothing between the words, site() did not run. Either the dotted path in TEMPLATES is wrong (it must be importable from the folder holding manage.py), or the page was rendered without the request, for example with get_template().render() and no request=, which skips every context processor.

Step 9: Error pages with a reference

Write the tests first, in config/tests/test_error_pages.py. They define their own URL configuration with a view that fails on purpose, because Otahque has no page that fails on demand.

"""Error pages that name the request's reference (Chapter 39)."""
import logging

from django.test import RequestFactory, TestCase
from django.test.utils import override_settings
from django.urls import path, reverse

from accounts.models import User
from config.helpers import save_event
from config.middleware import RequestIDFilter
from config.views import server_error


def broken(request):
    """Fail on purpose, for the 500 page."""
    raise ZeroDivisionError('a practice failure')


# A URLconf for ServerErrorTests: Django reads handler500
# from the root URLconf, so this one names it too.
urlpatterns = [path('broken/', broken)]
handler500 = 'config.views.server_error'


@override_settings(ROOT_URLCONF=__name__)
class ServerErrorTests(TestCase):
    """The 500 page and the log name the same reference."""

    def test_the_page_and_the_log_name_the_reference(self):
        self.client.raise_request_exception = False
        logger = logging.getLogger('django.request')
        logger.addFilter(RequestIDFilter())
        self.addCleanup(logger.filters.clear)
        with self.assertLogs('django.request') as logs:
            page = self.client.get('/broken/')
        reference = page['X-Request-ID']
        self.assertContains(page, reference, status_code=500)
        self.assertEqual(logs.records[0].request_id, reference)

    def test_the_page_needs_no_request_context(self):
        request = RequestFactory().get('/')
        request.id = 'abc123'
        page = server_error(request)
        self.assertContains(page, 'abc123', status_code=500)
        self.assertContains(page, 'support@otahque.example',
                            status_code=500)


class ProblemPageTests(TestCase):
    """403 and 404 pages explain, and name the reference."""

    def test_a_missing_page(self):
        page = self.client.get('/events/999999/')
        self.assertContains(page, 'This page is not here',
                            status_code=404)
        self.assertContains(page, page['X-Request-ID'],
                            status_code=404)

    def test_a_refused_page(self):
        event = save_event()
        sai = User.objects.create_user(
            'sai@example.org', display_name='Sai'
        )
        self.client.force_login(sai)
        page = self.client.get(
            reverse('registrations:attendees', args=[event.pk])
        )
        self.assertContains(page, 'You cannot open this page',
                            status_code=403)
        self.assertContains(page, page['X-Request-ID'],
                            status_code=403)

The 500 handler, in a new file config/views.py:

"""Views for the whole project (Chapter 39)."""
from django.conf import settings
from django.http import HttpResponseServerError
from django.template import loader


def server_error(request):
    """Show the 500 page, with the request's reference.

    Like Django's own, it renders without a RequestContext:
    context processors may need the database, which may be
    what failed. So it passes the few values it shows.
    """
    template = loader.get_template('500.html')
    return HttpResponseServerError(template.render({
        'site_name': settings.SITE_NAME,
        'support_email': settings.SUPPORT_EMAIL,
        'request_id': getattr(request, 'id', ''),
    }))

and at the end of config/urls.py:

# The 500 page shows the request's reference (Chapter 39).
handler500 = 'config.views.server_error'

Common Error: handler500 in the wrong file

Django looks for handler500 only in the root URL configuration, the module named by ROOT_URLCONF. In an app’s urls.py it is ignored, and so it is in a test that overrides ROOT_URLCONF with its own module: that is why test_error_pages.py names the handler too. Without it, the test’s 500 page is Django’s plain one and the reference test fails.

The 403 and 404 pages share one layout, templates/problem.html:

{% extends "base.html" %}
{# The error pages' layout (Chapter 39): what happened, #}
{# what to do, and the reference to quote. #}

{% block content %}
  <section class="problem-card" aria-labelledby="problem">
    <h1 id="problem">{% block heading %}{% endblock %}</h1>
    <p>{% block advice %}{% endblock %}</p>
    <p>If you write to
      <a href="mailto:{{ support_email }}">
        {{ support_email }}</a>, quote this reference:</p>
    <p class="reference"><code>{{ request_id }}</code></p>
    <a href="{% url 'events:list' %}" class="btn btn-primary">
      Go to the events</a>
  </section>
{% endblock %}

templates/403.html:

{% extends "problem.html" %}

{% block title %}Not allowed · Otahque{% endblock %}
{% block heading %}You cannot open this page{% endblock %}
{% block advice %}Your account does not have access to it.
  If you think it should, ask the event's organizer or
  write to us.{% endblock %}

templates/404.html:

{% extends "problem.html" %}

{% block title %}Not found · Otahque{% endblock %}
{% block heading %}This page is not here{% endblock %}
{% block advice %}The address may be mistyped, or the event
  may have been removed.{% endblock %}

and templates/500.html, which extends nothing, because base.html needs the user and the navigation, which the 500 page cannot rely on:

{% load static %}
<!doctype html>
{# Rendered without a RequestContext (config/views.py): #}
{# no user, no navigation, only what the view passes. #}
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport"
        content="width=device-width, initial-scale=1">
  <title>Something went wrong · {{ site_name }}</title>
  <link rel="stylesheet"
        href="{% static 'otahque/site.css' %}">
</head>
<body>
  <main id="main"
        class="mx-auto w-full max-w-6xl px-4 pt-6 pb-12">
    <section class="problem-card" aria-labelledby="problem">
      <h1 id="problem">Something went wrong</h1>
      <p>{{ site_name }} could not finish this page. Nothing
        you did caused it. Please try again in a minute.</p>
      <p>If it happens again, write to
        <a href="mailto:{{ support_email }}">
          {{ support_email }}</a> and quote this reference:</p>
      <p class="reference"><code>{{ request_id }}</code></p>
      <a href="/" class="btn btn-primary">Go to the home
        page</a>
    </section>
  </main>
</body>
</html>

The styles, in static/otahque/source.css, inside @layer components, above .form-actions:

  /* Help and references (Chapter 39): a footer on every
     page, and one card for the error pages, with the
     reference large enough to read from a screenshot. */
  .site-footer {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    gap: 0.5rem 1.5rem;
    padding: 1rem;
    border-top: 1px solid var(--color-base-300);
    background-color: var(--color-base-100);
    font-size: 0.875rem;
  }
  .problem-card {
    display: grid;
    gap: 0.75rem;
    justify-items: start;
    max-width: 40rem;
    padding: 1.5rem;
    border: 1px solid var(--color-base-300);
    border-left: 6px solid var(--color-warning);
    border-radius: var(--radius-box);
    background-color: var(--color-base-100);
  }
  .problem-card h1 {
    font-size: 1.5rem;
    font-weight: 700;
  }
  .reference code {
    display: inline-block;
    padding: 0.25rem 0.5rem;
    border-radius: var(--radius-field);
    background-color: var(--color-base-200);
    font-size: 1rem;
    overflow-wrap: anywhere;
  }
npm run build
uv run python manage.py test config.tests.test_error_pages
Found 4 test(s).
Creating test database for alias 'default'...
...
Ran 4 tests in ...s

OK

The test test_the_page_and_the_log_name_the_reference follows the same path as Figure 39.3: from Sai’s screen to the log line Sam finds.

Four numbered cards joined by arrows. 1, Sai sees Something went wrong; the page shows Reference 1f3a9c and so on. 2, she writes to support and pastes the reference. 3, Sam searches the log for 1f3a9c: one request, among thousands. 4, ERROR, 1f3a9c in square brackets, django.request: Internal Server Error, /events/7/register/, with the traceback.
Figure 39.3 — From a support report to a log line.

You see these pages only with DEBUG off. To look, stop the server and start it with DEBUG off for one run; --insecure lets runserver serve the stylesheet without DEBUG:

$env:DJANGO_DEBUG = "False"
$env:DJANGO_ALLOWED_HOSTS = "127.0.0.1"
uv run python manage.py runserver --insecure
DJANGO_DEBUG=False DJANGO_ALLOWED_HOSTS=127.0.0.1 \
  uv run python manage.py runserver --insecure

Open http://127.0.0.1:8000/events/999999/, and, signed in as a member who organizes nothing, another event’s attendee list. Figure 39.4 shows both. In PowerShell, close the window afterwards, or run Remove-Item Env:DJANGO_DEBUG, Env:DJANGO_ALLOWED_HOSTS, so the next runserver has DEBUG on again.

Two screenshots. Left, at 390 pixels: the page This page is not here, in a card with an amber edge, saying the address may be mistyped or the event removed, the support address, and a reference of 32 letters and digits in a grey box, with a Go to the events button; below, the footer with the support address and the same reference. Right, at 1280 pixels: You cannot open this page, the same card, with the navigation above and the footer below.
Figure 39.4 — The 404 page at 390 pixels and the 403 page at 1280 pixels.

Step 10: Order matters

Move 'django.contrib.auth.middleware.LoginRequiredMiddleware' in config/settings.py up, above AuthenticationMiddleware, and ask Django to check the project:

uv run python manage.py check
SystemCheckError: System check identified some issues:

ERRORS:
?: (auth.E013) In order to use
    django.contrib.auth.middleware.LoginRequiredMiddleware,
    django.contrib.auth.middleware.AuthenticationMiddleware
    must be defined before it in MIDDLEWARE.

System check identified 1 issue (0 silenced).

The check fails, and runserver and the tests would refuse to start: request.user would not exist yet when the middleware asked for it. Move the line back below AuthenticationMiddleware, and run the check again; it reports no issues. Django checks this one rule for you. For Otahque’s own middleware it does not: a middleware placed above AuthenticationMiddleware that reads request.user fails at the first request with AttributeError (interview question L4).

In practice: async views and this middleware

Situation. Chapter 53 adds asynchronous views. A middleware written as above is synchronous only.

Application. Django still runs it in an asynchronous server, adapting it in a thread for each request, which costs a little time. ContextVar keeps working, because each request runs in its own context.

Consideration. Chapter 53 makes RequestIDMiddleware support both modes, with Otahque's two other middleware classes, and adds a test that keeps every class in MIDDLEWARE able to run without a thread.

Step 11: Records and commit

In docs/design/permissions.md, at the end:

## Sign-in by default (Chapter 39)

LoginRequiredMiddleware sends a visitor to sign in for
every page whose view is not marked login_not_required.
Public: the home page, the event list, and the event
page, listed in config/tests/test_requests.py (PUBLIC),
and allauth's own pages. The per-view sign-in checks
(LoginRequiredMixin, login_required) were removed;
permission checks stay in the views. A visitor now gets
the sign-in page for every method on every other page.

and at the end of docs/adr/ADR-006-views.md:

## Update, Chapter 39

- LoginRequiredMiddleware answers visitors first, so
  rule 2's LoginRequiredMixin is gone from every view,
  and login_required from every function. Rule 2 for
  editing views becomes: ManageEventMixin, then the
  generic view, with http_method_names = ['get', 'post'].
- home, EventListView, and EventDetailView are marked
  login_not_required, the classes on dispatch().
- Register and the details page answer a visitor with
  the sign-in page for every method: eleven table rows
  changed, declared in registrations/tests/test_methods.py.

In docs/design/event-draft-form.md, “login_required” becomes “sign-in (LoginRequiredMiddleware, Chapter 39)” for the new-event page and “sign-in” for the edit page, and in docs/design/event-states.md the publish and cancel line starts “sign-in, require_POST”. Check and 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 436 test(s).
System check identified no issues (0 silenced).
Ran 436 tests in ...s
OK
== all checks passed
git add .
git status --short
git commit -m "Find each request by its reference"
M  .env.example
M  accounts/views.py
A  config/context_processors.py
A  config/middleware.py
M  config/settings.py
A  config/tests/test_error_pages.py
A  config/tests/test_public.py
A  config/tests/test_request_id.py
A  config/tests/test_site_values.py
M  config/urls.py
A  config/views.py
M  docs/adr/ADR-006-views.md
M  docs/design/event-draft-form.md
M  docs/design/event-states.md
M  docs/design/permissions.md
M  events/views.py
M  registrations/tests/test_methods.py
M  registrations/views.py
M  static/otahque/site.css
M  static/otahque/source.css
A  templates/403.html
A  templates/404.html
A  templates/500.html
M  templates/base.html
A  templates/includes/site_footer.html
A  templates/problem.html
[main 1a2b3c4] Find each request by its reference
 26 files changed, 543 insertions(+), 59 deletions(-)
 create mode 100644 config/context_processors.py
 create mode 100644 config/middleware.py
 create mode 100644 config/tests/test_error_pages.py
 create mode 100644 config/tests/test_public.py
 create mode 100644 config/tests/test_request_id.py
 create mode 100644 config/tests/test_site_values.py
 create mode 100644 config/views.py
 create mode 100644 templates/403.html
 create mode 100644 templates/404.html
 create mode 100644 templates/500.html
 create mode 100644 templates/includes/site_footer.html
 create mode 100644 templates/problem.html

If something goes wrong

Table 39.2 — Recovery for Chapter 39
Symptom Likely cause Recovery
The home page sends visitors to sign in home() not marked Add @login_not_required above it
A class-based public page sends visitors to sign in Decorator on the class Use method_decorator on dispatch
Django will not start: auth.E013 LoginRequiredMiddleware above AuthenticationMiddleware Move it below
AttributeError: 'WSGIRequest' object has no attribute 'id' RequestIDMiddleware missing from MIDDLEWARE Add it first in the list
Footer says "Write to ." site() not registered, or the page rendered without the request Check TEMPLATES and the view
404 shows Django's yellow page DEBUG is on Expected; run with DEBUG off to see Otahque's
The 500 page has no reference handler500 missing from the root URLconf Add it to config/urls.py
Chapter 29's log test fails A level set on the otahque logger Remove the level
PAGE 003

Verify Your Work

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

Table 39.3 — Verification checklist for Chapter 39
Check Command or action Expected result
Starting point test --parallel Found 423 test(s); OK
The Custom Way uv run python practice_chain.py in outer, in inner, the view, out inner, out outer
Request id test config.tests.test_request_id Red, then Found 4 test(s); OK
Sign-in by default test config.tests.test_public, then the suite One red; then 11 table rows red, declared; Found 430 test(s); OK
Redundant checks removed test --parallel Found 430 test(s); OK
Site values test config.tests.test_site_values Found 2 test(s); OK
Error pages test config.tests.test_error_pages Found 4 test(s); OK
UI 404 and 403 pages, and the footer, at 390 and 1280 px, DEBUG off A card with the reference; no sideways scroll
Order LoginRequiredMiddleware moved up, then check auth.E013; moved back
All checks uv run python check.py == all checks passed; Ran 436 tests
Commit git log --oneline -1 Find each request by its reference
Not verified macOS and Linux shells; browsers other than Edge; an asynchronous server Chapter 53 runs the middleware under ASGI; Chapter 64 adds CI on Linux

The commands were checked in Windows PowerShell 5.1 and Git Bash, from a copy of the Chapter 38 checkpoint with a reader’s data, against PostgreSQL 18; commands that write files ran once. The project folder is shortened to ... in printed output. The screenshots were taken in Microsoft Edge with DEBUG off, with one sample event added for the screenshots only and deleted afterwards.

PAGE 004

Checkpoint: Quiz and Challenge

Quiz

Que. 1 In what order do two middleware, listed as [A, B], see a request and its response?

Flip to check your answerFold answer back

Answer. A sees the request first, then B, then the view. The response goes back through B first, then A. Each one wraps the next, so the first in the list is the outermost layer.

Que. 2 Why does Otahque ignore an X-Request-ID header a browser sends?

Flip to check your answerFold answer back

Answer. Anyone can send that header. Trusting it would let a visitor give their requests another member’s id and confuse the logs. Otahque makes a new id for every request until a proxy it controls sets the header (Chapter 63).

Que. 3 A view has no decorator and no mixin. Can a signed-out visitor open it?

Flip to check your answerFold answer back

Answer. No. LoginRequiredMiddleware sends them to sign in, because the view is not marked login_not_required. Only the three marked pages, and allauth’s pages, are open to visitors.

Que. 4 Why must site() run no database query?

Flip to check your answerFold answer back

Answer. Django calls every context processor for every page rendered with the request, including pages that never use the values and the 403 and 404 pages. A query there would run on every page. site() reads settings and the request only, and a test pins zero queries.

Que. 5 Why is the 500 page rendered by Otahque’s own handler, without a request context?

Flip to check your answerFold answer back

Answer. It appears when something failed, possibly the database or the session. Context processors such as auth may need them, so rendering with a request context could fail again. The handler passes the three values the page shows, none of which needs the database.

Mini-Challenge

Write a test, in config/tests/test_header.py, that a visitor’s request for My registrations, which the middleware answers with a redirect to sign in, still carries a 32-character X-Request-ID.

Hint: the redirect is made by a middleware below RequestIDMiddleware, so the response passes back through it.

Model answer:

"""Every response carries a reference (Chapter 39)."""
from django.test import TestCase


class HeaderEverywhereTests(TestCase):
    """Even a redirect to sign in has an X-Request-ID."""

    def test_a_redirect_has_a_reference(self):
        page = self.client.get('/registrations/')
        self.assertEqual(page.status_code, 302)
        self.assertEqual(len(page['X-Request-ID']), 32)
Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...s

OK

LoginRequiredMiddleware answers without calling the view, but the response still travels back up through every middleware above it, and RequestIDMiddleware is the first. The model answer was run and then removed; the chapter’s checkpoint does not include it.

What We Learned

  • A middleware is a callable built once with the next handler; for each request it may work before and after calling it.
  • MIDDLEWARE lists layers from the outside in; the response returns in reverse order.
  • A middleware may answer by itself, and the layers below never see the request.
  • A ContextVar set by a middleware and read by a logging filter puts one id on every log line of a request.
  • LoginRequiredMiddleware makes sign-in the default; login_not_required marks a public view, on dispatch() for a class.
  • Sign-in is not permission: object checks stay in the views.
  • A context processor runs for every page rendered with the request; keep it free of queries.
  • 403.html and 404.html get the request context; the 500 page needs its own handler, in the root URLconf.

Key terms

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

Table 39.4 — Key terms from Chapter 39
Term Meaning
Middleware A layer every request and response passes through.
get_response The next handler, given to a middleware when the chain is built.
Request id A random value that names one request, on its page and in its log lines.
Context variable A value held per thread or per task, such as the current request's id.
Logging filter Code that may change or drop a log record before a handler writes it.
Deny by default Refuse unless something explicitly allows.
LoginRequiredMiddleware Django's middleware that sends visitors to sign in unless a view is marked public.
login_not_required The decorator that marks a view public.
Context processor A function that adds values to every template rendered with the request.
handler500 The view Django calls for a server error, named in the root URLconf.

Readiness checkpoint: you are ready for Chapter 40 when uv run python check.py ends with “all checks passed” and 436 tests, a signed-out visitor can open only the home page, the event list, and event pages, every page’s footer shows a reference that matches its X-Request-ID header, and git log --oneline -1 shows this chapter’s commit.

Git Commit

Your Chapter 39 work was committed once, in Step 11, as “Find each request by its reference”: the middleware and its settings, the logging, the public pages and the removed sign-in checks, the method tables, the context processor, the footer and error pages, the styles, the tests, and the design notes. If you kept the Mini-Challenge, commit it on its own:

git add config/tests/test_header.py
git commit -m "Check a redirect has a reference"
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 a common ordering failure and to where authorization belongs. They are extension questions, not a gate to the next chapter. Proof files are run with uv run python manage.py shell -v 0 -c "exec(open('NAME').read())" and deleted afterwards.

L1 (Junior): What is the difference between a middleware and a decorator?

What the interviewer is testing: Do you know where each one applies?

Flip to check your answerFold answer back

Perfect answer: A decorator wraps one view: it runs only for the requests that reach that view, and only if someone remembered to write it. A middleware wraps every request the project handles, listed once in MIDDLEWARE, including requests for pages that do not exist. Both can work before and after the code they wrap, and both can answer by themselves. Use a decorator for a rule that belongs to some views, such as require_POST, and middleware for a rule that belongs to all of them, such as a request id. Django’s LoginRequiredMiddleware turns sign-in from the first kind into the second, with login_not_required as the exception.

Table 39.5 — A decorator and a middleware
Question Decorator Middleware
Applies to One view Every request
Written Above the view Once, in MIDDLEWARE
Sees a missing page No Yes
Forgotten on a new view The rule is missing Cannot be forgotten

Behind the scenes:

view = resolve(request.path).func
getattr(view, 'login_required', True)
True and visitor -> redirect to sign in

Code proof: the attribute on three pages:

/ login_required: False
/events/ login_required: False
/registrations/ login_required: True

Common mistakes:

  • Thinking a middleware runs only for views that exist; it runs for 404s too.
  • Using middleware for a rule that only two views need.

Follow-up the interviewer might ask:

  • Can a middleware see which view will run? (Yes, in process_view(), which LoginRequiredMiddleware uses.)
  • Which runs first, a middleware or a view’s decorator? (The middleware.)

L2 (Mid-Level): Predict what a new page without any decorator does for a visitor

What the interviewer is testing: Do you understand deny by default in practice?

Flip to check your answerFold answer back

Perfect answer: Raj adds /events/7/report/ with a plain function view and no decorator. A visitor who opens it is redirected to the sign-in page with ?next=/events/7/report/, because the middleware reads the view’s login_required attribute, which is missing and so counts as True. Nothing about the new view had to be remembered. If Raj wanted it public, he would have to add login_not_required, and the public-pages test would fail until PUBLIC lists it, which puts the decision in front of a reviewer.

A numbered flow of five cards. 1, a visitor opens a new page, /events/7/report/. 2, its view has no decorator at all. 3, the middleware reads view.login_required: True. 4, 302 to sign in, with next set to the page. 5, the public-pages test still lists three.
Figure 39.5 — A new page without a decorator.

Behind the scenes:

events/views.py   @login_not_required
test_public.py    PUBLIC = {..., 'events:report'}

Code proof: the public-pages tests:

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

OK

Common mistakes:

  • Marking a page public that shows one member’s data.
  • Testing only that public pages open, not that the set is exact.

Follow-up the interviewer might ask:

  • What about a webhook from another service? (Public, with its own signature check.)
  • Does the middleware cover the admin? (The admin’s own views send visitors to its sign-in page, which Otahque sends on to allauth’s.)

L3 (Senior): Defend a context processor that runs no queries

What the interviewer is testing: Can you weigh the cost of code that runs on every page?

Flip to check your answerFold answer back

Perfect answer: A context processor runs for every page rendered with the request: lists, forms, error pages, and pages that never show its values. A query there, such as “how many upcoming registrations does this member have” for a badge, would add one query to every page, the error pages included. site() returns settings and request.id, which cost nothing, and a test pins zero queries with assertNumQueries(0). A per-member count belongs to the page that shows it, or, if every page shows it, to a cached value with a known cost, measured first in Chapter 55.

A numbered flow of five cards. 1, a context processor runs for every page. 2, a query there runs on every page, errors too. 3, so: settings and the request only. 4, assertNumQueries(0) pins it. 5, per-member counts belong in their own view.
Figure 39.6 — Why the context processor runs no queries.

Behind the scenes:

render(request, ...) -> each processor in TEMPLATES
request, auth, messages, site -> one context

Code proof: site()’s values, and its queries:

['request_id', 'site_name', 'support_email'] queries: 0

Common mistakes:

  • Assuming lazy values are free: auth’s user is lazy, but touching it in the footer would query.
  • Measuring with an empty database and seeing no cost.

Follow-up the interviewer might ask:

  • How would you show a count on every page? (Cache it per member, and expire it when a registration changes.)
  • Does site() run for the 500 page? (No: the handler renders without a request context.)

L4 (Staff): “AttributeError: ’WSGIRequest’ object has no attribute ’user’”. Diagnose it

What the interviewer is testing: Can you read a middleware failure back to the list’s order?

Flip to check your answerFold answer back

Perfect answer: Something read request.user before AuthenticationMiddleware set it. The traceback names the code; if it is a middleware, it is listed above AuthenticationMiddleware in MIDDLEWARE, so on the way in it runs first. I would read the list from the top, move the middleware below AuthenticationMiddleware, and add a test that the page works with a signed-in member. Django guards its own case: LoginRequiredMiddleware above AuthenticationMiddleware is refused at startup with auth.E013, as Step 10 showed. For Otahque’s own middleware there is no such check, which Chapter 40’s system checks could add.

A numbered flow of five cards. 1, AttributeError: no attribute user. 2, read MIDDLEWARE from the top. 3, our middleware is above AuthenticationMiddleware. 4, move it below: request.user exists there. 5, Django’s auth.E013 guards LoginRequired’s place.
Figure 39.7 — A middleware placed too early.

Behind the scenes:

SessionMiddleware         request.session
AuthenticationMiddleware  request.user
YourMiddleware            request.user is here

Code proof: Django’s own check, from Step 10:

SystemCheckError: System check identified some issues:

ERRORS:
?: (auth.E013) In order to use
    django.contrib.auth.middleware.LoginRequiredMiddleware,
    django.contrib.auth.middleware.AuthenticationMiddleware
    must be defined before it in MIDDLEWARE.

System check identified 1 issue (0 silenced).

Common mistakes:

  • Adding hasattr(request, 'user') and silently skipping the work.
  • Moving the middleware to the bottom without checking what depends on it.

Follow-up the interviewer might ask:

  • Where must RequestIDMiddleware go? (First, so every response and log line has the id.)
  • Why does order matter on the way out too? (A middleware that changes the response must be above any that reads it.)

L5 (Lead): Defend keeping authorization out of middleware

What the interviewer is testing: Can you place a rule where it has the information it needs?

Flip to check your answerFold answer back

Perfect answer: A colleague proposes one middleware that checks every permission, so views stay simple. But “may Raj edit event 7” depends on event 7’s organizers, which only the view loads, after it knows which event and why. A middleware sees the path and the view, not the object. It would have to load the event itself, duplicating the view’s query, or guess from the URL, which breaks when a URL changes. Otahque’s split: the middleware answers the one question that holds for every request, “is someone signed in?”; the views answer object questions with ManageEventMixin and deny(), with the right 404 or 403 and a refusal record. I would revisit if a rule truly applied to every request, such as a site-wide maintenance mode.

A numbered flow of five cards. 1, proposal: check every permission in middleware. 2, middleware sees a URL, not event 7’s organizers. 3, only the view loads the event it acts on. 4, middleware: one yes or no, signed in. 5, views: 404 or 403, recorded, per object.
Figure 39.8 — Where each kind of check belongs.

Behind the scenes:

middleware  path, user, the view function
view        the event, its organizers, the action

Code proof: what LoginRequiredMiddleware is given:

(self, request, view_func, view_args, view_kwargs)

Common mistakes:

  • Parsing ids out of the URL in middleware.
  • Answering 403 for a hidden draft, which tells a visitor it exists.

Follow-up the interviewer might ask:

  • Where would a maintenance mode go? (Middleware: it applies to every request.)
  • How do you prove no view lost its object check? (The permission matrix tests from Chapter 30 still run.)
PAGE 006