Chapter 37 · Generic editing views and access mixinsCHAPTER 37
Complete six-part pre-release for review. No new package and no migration. Signed-out visitors now get the sign-in page for every method on the editing pages, and those pages answer only GET and POST (declared changes). ADR-006's rule that one-off actions stay functions is superseded: views become classes when a chapter next changes them.
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-SEVEN
Generic editing views and access mixins
Stage 5: Growing the application (Chapters 35 to 46)
Prerequisites: Chapters 9 to 36, including the Chapter 36 project with its 391 passing tests, the method tables and answers(), ADR-006; the access rules in Event methods and deny() (Chapter 30); save_edit() with its lock and version check (Chapter 33); Python classes and super() (Chapter 4)
What you’ll build: Method tables for the six pages that change data, written while they are still functions; Python’s method resolution order tried by hand; ManageEventMixin, one access check shared by every page that changes an event; the edit, create, delete, and copy pages, the cancel-registration page, and the profile page as generic editing views; a comparison with UserPassesTestMixin, and the leak a mixin in the wrong place causes; an edit form in labelled groups with a marked danger area; and ADR updates that say what changed
Why This Matters
Sam edits his Python clinic most weeks. Raj organizes a different event, so he has the same permission to change events, but not Sam’s. If Raj copies the address of Sam’s edit page and changes the number in it, he must be refused: with 404 if Sam’s event is still a draft, so Raj learns nothing about it, and with 403 if it is published. And the attempt must be recorded, because Chapter 30 decided that an administrator should see who tried what.
Today that check lives in event_to_manage(), and five views call it: edit, publish, cancel, delete, and copy. Each is a function that loads the event, checks the rule, and then does its own work. The repetition is small, but each copy is a place where the check can be forgotten. A page that changes something and forgets the check is called an insecure direct object reference (IDOR): anyone who guesses a number can reach someone else’s record. It is one of the most common security bugs in web applications, and it is never loud. The page just works, for the wrong person.
Django’s generic editing views do for forms what Chapter 36’s display views did for lists: CreateView, UpdateView, DeleteView, and FormView show a form, check it, and save it. And Django’s access mixins, small classes you add to a view, check who may use it before it runs. This chapter puts Otahque’s rule in one mixin, tested once against the permission matrix, and builds every editing page on it.
Two traps come with the convenience, and the chapter shows both on purpose. A mixin written in the wrong place in a class’s list of parents does nothing at all, and the page works for everyone. And Django’s DeleteView answers one kind of request in a way that skips your own code entirely. Neither shows up in Otahque’s existing tests; both show up in the tests you will write first.
By the end of the chapter, you will be able to:
explain what CreateView, UpdateView, DeleteView, and FormView do, and where your code goes in each;
read a class’s method resolution order and predict which parent’s method runs;
write an access mixin that keeps a rule in the model and records refusals, and compare it with Django’s UserPassesTestMixin;
convert an editing page to a class without losing its lock, its version check, or its records;
close the HTTP methods a page should never answer;
record a superseded decision openly in an ADR.
Out of scope: per-event registration questions on the edit page (Chapter 38), sign-in for every page by default (Chapter 39), permissions in the API (Chapter 50), and converting publish and cancel, which become classes when a chapter next changes them.
What problem exists? Every page with a form repeats one shape: on GET, show an empty or filled form; on POST, bind the form to what was sent, check it, and either save and redirect or show the form again with its errors.
What did people do before? Wrote if request.method == 'POST': in every view, as Otahque’s functions do.
What is it?FormView shows and checks any form. CreateView and UpdateView do the same for a ModelForm, and UpdateView first fetches the object with get_object(). DeleteView fetches an object, shows a confirmation page on GET, and deletes on POST. Each calls form_valid() when the form is good and form_invalid() when it is not.
Why use them? The branching, the binding, and the redirect are written once, in Django. You write what happens when the form is good.
Now let’s use it. Steps 4, 6, and 7 convert six pages.
Table 37.1 lists the hooks this chapter overrides. They join the display hooks from Chapter 36: every editing view that works on one object is also a SingleObjectMixin, so get_object() and pk_url_kwarg mean what they meant there.
Table 37.1 — The parts of a generic editing view this chapter uses
Name
What it does
form_class
The form to show and check
get_form_kwargs()
The arguments the form is made with; add your own, such as the event
get_initial()
Starting values for an unbound form
form_valid(form)
Runs when the form is good: save, then return a response, usually a redirect
get_success_url() or success_url
Where to go after form_valid(), if it does not redirect itself
get_object()
UpdateView and DeleteView: the object the page works on
http_method_names
The HTTP methods the view answers; any other gets 405
Under the Hood: what the generic views answer that you never wrote
Chapter 35 showed that a class answers some requests before your code runs. The editing views add two surprises. ProcessFormView, the parent of CreateView, UpdateView, and FormView, defines put() as “the same as post()”, so those views list PUT in their Allow header and treat a PUT as a form submission. Django only reads form data from POST bodies, so the form is empty and fails; the page answers 200 with errors. And DeleteView inherits delete() from DeletionMixin, which fetches the object and calls its delete() method directly, without a form and without form_valid(). Since Django 4.0, a POST to a DeleteView goes through form_valid(), where your own rules live. A DELETE request does not.
Mixins and the method resolution order
A mixin is a class that is not meant to be used alone. It adds one ability to any class that lists it as a parent. LoginRequiredMixin adds “send visitors to sign in”; Otahque’s ManageEventMixin will add “fetch the event only for someone who may change it”. A class with several parents still has to decide, for each method name, whose method to use. Python decides with the method resolution order (MRO), a single list of the class and all its parents, which you can read as ClassName.__mro__. To find a method, Python walks the list from the left and uses the first class that defines it. super() continues along the same list from where the current method was found.
For classes with one line of parents, the MRO is simply the class, its parent, its parent’s parent. With several parents it is more complex, but for the views in this book one rule is enough: the parents you list come in the order you list them, before the parents they share. So class EventUpdateView(LoginRequiredMixin, ManageEventMixin, UpdateView) looks in the class itself, then LoginRequiredMixin, then ManageEventMixin, then UpdateView and its parents. Write the mixins to the left of the generic view. Figure 37.1 shows what happens if you do not.
Figure 37.1 — The same three parents in two orders.
Where the access check belongs
Django offers three ways to check access on a class view, and Otahque uses its own fourth. Table 37.2 compares them against Otahque’s rule: 404 for a hidden event, 403 for a visible one, and a record either way.
Table 37.2 — Ways to guard an editing page
Way
What it checks
Against Otahque's rule
LoginRequiredMixin
Signed in
Needed, not enough
PermissionRequiredMixin
A permission, optionally on an object
has_perm(perm, obj) is True for any superuser (Chapter 30); no 404, no record
UserPassesTestMixin
Your test_func() returns True
Always 403; no record
ManageEventMixin (Otahque)
Event methods, through deny()
404 or 403, recorded
UserPassesTestMixin is the way most tutorials show. It is not wrong; it is a different rule. Step 5 builds it on the edit page beside Otahque’s mixin, so you can see the difference in answers rather than take it on trust.
Otahque’s mixin overrides get_object(). That is the one method every page that works on an existing event calls to fetch it, so the check cannot be skipped by a page that fetches the event some other way, and the event is fetched once. get_object() runs inside the handler, after dispatch() has checked the method, so a PUT is refused with 405 before the event is even looked at, and is not recorded: the same order Chapter 35 accepted for the event page.
Figure 37.2 — A POST through EventUpdateView.
When the generic path is not enough
UpdateView’s own post() fetches the object, binds the form, checks it, and calls form_valid(). Otahque’s edit page cannot use it as it is. Chapter 33 made the edit check the form against the event’s row while that row is locked, so that “capacity cannot drop below the places taken” counts the places taken now, not a moment ago, and so that a save from an old page is refused by the version number. save_edit() does that, inside one transaction. The generic post() would check the form before any lock. So EventUpdateView keeps UpdateView for GET, and writes its own post() that calls save_edit(). A generic view is a starting point you are allowed to override, not a contract to use every part of it.
In practice: auditing a codebase for IDOR
Situation. A team inherits a project with forty views that take an id from the address.
Application. They list every view that fetches an object by id and check where its access rule is applied. Views that share one mixin need one test of the mixin and one test that each view uses it; views with their own checks need a test each.
Consideration. A test that the mixin is first in each view’s MRO, like Step 6’s, is cheap insurance: it fails the moment someone reorders the parents.
Start from Chapter 36, in the folder containing manage.py, with Otahque on PostgreSQL 18, 391 passing tests, and the work committed (the last commit is “Page and filter the event lists”). No package, model, or migration changes. The new files are config/tests/test_editing_methods.py, events/tests/test_editing.py, and events/templates/events/event_fields.html. events/views.py, events/urls.py, registrations/views.py, registrations/urls.py, accounts/views.py, accounts/urls.py, three event templates, the stylesheet source, ADR-004, and ADR-006 change. The visible result: the new and edit pages show their fields in three labelled groups, About the event, When, and Registration, with one action bar, and a draft’s edit page ends with a marked area for deleting it. The chapter’s commands were checked in Windows PowerShell 5.1 and Git Bash against PostgreSQL 18.
The Custom Way
Before you trust Python to pick the right parent’s method, watch it do so with three tiny classes and no Django. Step 3 does it, after Step 2 has pinned the six pages’ answers.
The Django Way
Step 1: Check the starting point
Terminal
uv run python manage.py test --parallel
Output
Found 391 test(s).
Creating test database for alias 'default'...
...
Ran 391 tests in ...s
OK
Terminal
git status --short
git log --oneline -1
Output
... Page and filter the event lists
Step 2: Pin the six pages’ answers
Six pages change data: new event, edit, delete, copy, cancel a place, and the profile. Read each function’s decorators. event_create, event_edit, and profile have only login_required, and no method check, so every method gets the page. event_delete, event_copy, and cancel_registration have require_http_methods(['GET', 'POST']) above login_required, so a wrong method gets 405 before sign-in is considered. event_create also refuses a member without add_event, and the edit, delete, and copy pages refuse a member who does not organize the event, both recorded.
The pages belong to three apps, so their table goes in config/tests/, beside Chapter 34’s acceptance tests. Create config/tests/test_editing_methods.py:
config/tests/test_editing_methods.py
"""How the six editing pages answer every method (37).
Written while they were functions; the rows that changed
when they became classes are declared in the tables.
"""
from datetime import timedelta
from django.test import TestCase
from django.utils import timezone
from config.helpers import answers, in_group, save_event
from registrations.models import Registration
from registrations.tests.test_registrations import verified
EVERY = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE',
'OPTIONS', 'TRACE']
SENT = ('GET', 'POST')
ONLY = '405 GET, POST'
# No method check: every method gets the page.
ANY_METHOD = [(method, 'sign in', 'ok') for method in EVERY]
# require_http_methods(['GET', 'POST']) above sign-in.
GET_POST = [
(method, 'sign in' if method in SENT else ONLY,
'ok' if method in SENT else ONLY)
for method in EVERY
]
EDIT_NOT_THEIRS = [
(method, 'sign in', '403 recorded') for method in EVERY
]
NOT_THEIRS = [
(method, 'sign in' if method in SENT else ONLY,
'403 recorded' if method in SENT else ONLY)
for method in EVERY
]
NO_ADD_PERMISSION = [
(method, 'sign in', '403 recorded') for method in EVERY
]
class EditingMethodTests(TestCase):
"""The editing pages' answers to each method, pinned."""
@classmethod
def setUpTestData(cls):
cls.sam = in_group('sam@example.org', 'Organizers')
cls.raj = in_group('raj@example.org', 'Organizers')
cls.sai = verified('sai@example.org')
cls.event = save_event(
starts_at=timezone.now() + timedelta(days=7)
)
cls.event.add_organizer(cls.sam)
save_event().add_organizer(cls.raj)
def check(self, path, member, table):
"""Compare the page's answers with each row."""
for method, signed_out, signed_in in table:
with self.subTest(path=path, method=method):
self.assertEqual(
answers(path, member, method),
(signed_out, signed_in),
)
def test_create(self):
self.check('/events/new/', self.sam, ANY_METHOD)
def test_create_without_permission(self):
self.check('/events/new/', self.sai, NO_ADD_PERMISSION)
def test_each_event_page_for_its_organizer(self):
event = self.event.pk
self.check(f'/events/{event}/edit/', self.sam,
ANY_METHOD)
for page in ('delete', 'copy'):
self.check(f'/events/{event}/{page}/', self.sam,
GET_POST)
def test_each_event_page_for_another_organizer(self):
event = self.event.pk
self.check(f'/events/{event}/edit/', self.raj,
EDIT_NOT_THEIRS)
for page in ('delete', 'copy'):
self.check(f'/events/{event}/{page}/', self.raj,
NOT_THEIRS)
def test_cancel_registration(self):
place = Registration.objects.create(event=self.event,
member=self.sai)
self.check(f'/registrations/{place.pk}/cancel/',
self.sai, GET_POST)
def test_profile(self):
self.check('/accounts/profile/', self.sai, ANY_METHOD)
SENT names the two methods the forms send. Each table is built from EVERY with a list comprehension, and the conditional expression 'ok' if method in SENT else ONLY picks a row’s answer. Sam organizes the event; Raj is an organizer too, of another event; Sai is a member. A POST with no data is harmless on every page: the forms fail, the delete page refuses a published event, and cancelling Sai’s place is what the cancel page is for. Run the table:
Terminal
uv run python manage.py test config.tests.test_editing_methods
Output
Found 6 test(s).
Creating test database for alias 'default'...
...
Ran 6 tests in ...s
OK
Green on the functions.
Step 3: The Custom Way: which parent’s method runs
Create practice_mro.py beside manage.py. It is plain Python:
practice_mro.py
"""Practice: the order Python gives a class's parents.
Plain Python, no Django. Run it once, then delete it.
"""
class View:
def get_object(self):
return 'any event, by its number'
def get(self):
return f'the page for {self.get_object()}'
class CheckMixin:
def get_object(self):
return 'an event this member may change'
class Right(CheckMixin, View):
pass
class Wrong(View, CheckMixin):
pass
class Noted(CheckMixin, View):
def get(self):
return 'noted, then ' + super().get()
for cls in (Right, Wrong, Noted):
names = [parent.__name__ for parent in cls.__mro__]
print(cls.__name__, names)
print(' get():', cls().get())
Terminal
uv run python practice_mro.py
Output
Right ['Right', 'CheckMixin', 'View', 'object']
get(): the page for an event this member may change
Wrong ['Wrong', 'View', 'CheckMixin', 'object']
get(): the page for any event, by its number
Noted ['Noted', 'CheckMixin', 'View', 'object']
get(): noted, then the page for an event this member may
change
Right lists CheckMixin first, so its get_object() is found first and View.get() uses it: the page is for “an event this member may change”. Wrong has the same two parents in the other order, and View’s own get_object() wins. Nothing fails; the check is simply never called. Noted shows super(): its get() runs, then hands over to the next get() in the MRO, which is View’s, which calls the get_object() found first, CheckMixin’s. Delete the file.
Step 4: ManageEventMixin and the edit page
In events/views.py, import LoginRequiredMixin beside PermissionRequiredMixin:
events/views.py
from django.contrib.auth.mixins import (
LoginRequiredMixin, PermissionRequiredMixin,
)
and UpdateView beside the display views:
events/views.py
from django.views.generic import (
DetailView, ListView, UpdateView,
)
Add the mixin after event_to_manage(), above STALE:
events/views.py
class ManageEventMixin:
"""Fetch the address's event if this member may change it.
Write it left of the generic view: LoginRequiredMixin,
then this mixin, then the view. A refusal is recorded
as an attempt at manage_action: 404 if the event is
hidden, 403 if not (Chapter 30).
"""
manage_action = None
def get_object(self, queryset=None):
"""Return the event, or refuse with deny()."""
return event_to_manage(self.request,
self.kwargs['event_id'],
self.manage_action)
It is four lines of code, because the rule already exists: event_to_manage() fetches the event, calls deny() with hidden=True if this member may not see it, and calls deny() again if they may see it but not change it. self.kwargs holds the address’s values, as in Chapter 35’s views. Each view says which action a refusal records with manage_action. The mixin overrides get_object() without calling super(), on purpose: there is no other way to fetch an event that a view should fall back to.
Now replace event_edit with:
events/views.py
class EventUpdateView(LoginRequiredMixin, ManageEventMixin,
UpdateView):
"""Edit the event, for those who may change it.
GET is UpdateView's own. post() keeps save_edit(), so
the form is checked on the locked row (Chapter 33).
"""
form_class = EventForm
template_name = 'events/edit.html'
manage_action = Action.EDIT_EVENT
http_method_names = ['get', 'post']
def get_object(self, queryset=None):
"""Fetch the event; keep its title for the page."""
event = super().get_object(queryset)
self.title = event.title
return event
def post(self, request, *args, **kwargs):
"""Save under the lock, or show the form again."""
self.object = self.get_object()
try:
form = save_edit(request, self.object)
except ValidationError as error:
refuse(request, error)
form = EventForm(request.POST,
instance=self.object)
if form is None:
messages.success(request, 'Changes saved.')
return redirect(self.object)
return self.render_to_response(
self.get_context_data(form=form)
)
def get_context_data(self, **kwargs):
"""Add the title as saved, and the places taken."""
return super().get_context_data(**kwargs) | {
'title': self.title,
'taken': self.object.places_taken(),
}
The parents are in the order the docstring promises: sign-in, the rule, the generic view. http_method_names closes PUT and the rest. get_object() calls the mixin’s, then keeps the event’s title as saved, because the page’s heading must not change to a half-typed title when a form comes back with errors; the function did the same with a local variable. GET is UpdateView’s: it calls get_object(), builds EventForm with the event as its instance, and renders. post() is written out, because the form must be checked under the lock: it fetches the event through the mixin, then hands over to Chapter 33’s save_edit(), exactly as the function did. get_context_data() adds the title and the places taken; UpdateView already added form and event.
The template named the event’s number event_id, which the function passed. A generic view passes the event itself, so in events/templates/events/edit.html, the link back reads:
events/templates/events/edit.html
<a href="{{ event.get_absolute_url }}">
Run the events app’s tests. They include Chapter 33’s lock tests, which run on PostgreSQL:
Terminal
uv run python manage.py test events --parallel
Output
Found 213 test(s).
Creating test database for alias 'default'...
...
Ran 213 tests in ...s
OK
Every edit test passes: the permission matrix, the zone confirmation, the stale version, the busy lock, and the crafted fields. The method table is not in this run; Step 8 reads it once all six pages have changed.
Common Error: letting UpdateView save
If you delete post() because UpdateView “already saves”, the page still opens and still saves a good form. Five of Otahque’s tests fail, and between them they name everything the generic post() skips: the busy lock (BusyEditTests), the version check (EditVersionTests, twice), the message after a save, and the edit’s record in the audit trail. A generic method that is right for most projects can be wrong for a rule your project made, and the tests you wrote for that rule are how you find out.
Step 5: Two other ways, and why not
Before converting the other pages, compare. Create events/tests/test_compare.py, a test module that adds two practice pages to Otahque’s addresses for the length of the test:
events/tests/test_compare.py
"""Practice: two other ways to guard the edit page (37).
Run it once, then delete it: it is not part of Otahque.
"""
from django.contrib.auth.mixins import (
LoginRequiredMixin, UserPassesTestMixin,
)
from django.test import TestCase, override_settings
from django.urls import path
from django.views.generic import UpdateView
from audit.models import AuditEvent
from config.helpers import in_group, save_event
from config.urls import urlpatterns as otahque
from events.forms import EventForm
from events.models import Event
from events.views import ManageEventMixin
class TestFuncEdit(LoginRequiredMixin, UserPassesTestMixin,
UpdateView):
"""Option B: the rule as test_func()."""
model = Event
form_class = EventForm
pk_url_kwarg = 'event_id'
def test_func(self):
"""Allow only members who may change the event."""
event = self.get_object()
return event.can_be_edited_by(self.request.user)
class WrongOrderEdit(LoginRequiredMixin, UpdateView,
ManageEventMixin):
"""The access mixin written right of the view."""
model = Event
form_class = EventForm
pk_url_kwarg = 'event_id'
template_name = 'events/delete.html'
urlpatterns = otahque + [
path('practice/b/<int:event_id>/', TestFuncEdit.as_view()),
path('practice/wrong/<int:event_id>/',
WrongOrderEdit.as_view()),
]
@override_settings(ROOT_URLCONF='events.tests.test_compare')
class CompareTests(TestCase):
"""Raj organizes another event, never Sam's."""
@classmethod
def setUpTestData(cls):
sam = in_group('sam@example.org', 'Organizers')
cls.raj = in_group('raj@example.org', 'Organizers')
cls.draft = save_event(status=Event.Status.DRAFT)
cls.draft.add_organizer(sam)
cls.event = save_event()
cls.event.add_organizer(sam)
save_event().add_organizer(cls.raj)
def setUp(self):
self.client.force_login(self.raj)
def test_a_hidden_draft_a_404_b_403(self):
n = self.draft.pk
for path_, status in [(f'/events/{n}/edit/', 404),
(f'/practice/b/{n}/', 403)]:
with self.subTest(path_):
response = self.client.get(path_)
self.assertEqual(response.status_code, status)
def test_a_records_the_attempt_b_does_not(self):
refused = AuditEvent.objects.filter(
outcome=AuditEvent.Outcome.REFUSED
)
self.client.get(f'/events/{self.event.pk}/edit/')
self.assertEqual(refused.count(), 1)
self.client.get(f'/practice/b/{self.event.pk}/')
self.assertEqual(refused.count(), 1)
def test_the_wrong_order_lets_raj_in(self):
response = self.client.get(
f'/practice/wrong/{self.event.pk}/'
)
self.assertEqual(response.status_code, 200)
TestFuncEdit is option B: UserPassesTestMixin calls test_func(), and a False answer is 403. WrongOrderEdit uses Otahque’s own mixin, written after UpdateView. override_settings(ROOT_URLCONF=...) makes this module the project’s URL list during the tests: Otahque’s patterns, plus the two practice addresses. Run it:
Terminal
uv run python manage.py test events.tests.test_compare
Output
Found 3 test(s).
Creating test database for alias 'default'...
...
Ran 3 tests in ...s
OK
Three facts, each a test. For Sam’s hidden draft, Otahque’s page answers 404 and option B answers 403, which tells Raj that a draft with that number exists. For Sam’s published event, Otahque’s page records Raj’s attempt and option B records nothing. And with the mixin written last, Raj gets Sam’s page: the leak from Step 3, in a real view. Figure 37.3 sums it up. Delete test_compare.py; it has made its point.
Figure 37.3 — Otahque’s mixin and UserPassesTestMixin, by what Raj gets.
Step 6: Create, delete, and copy
Write the tests first. Create events/tests/test_editing.py:
events/tests/test_editing.py
"""The editing views and ManageEventMixin (Chapter 37)."""
from django.test import SimpleTestCase, TestCase
from audit.models import AuditEvent
from config.helpers import in_group, save_event
from events import views
from events.models import Event
def first_get_object(view):
"""Return the class whose get_object() the view's calls.
The view's own method is skipped, because it calls
super(); the next one in the MRO is the one that
fetches the event.
"""
return next(cls for cls in view.__mro__[1:]
if 'get_object' in vars(cls))
class MixinOrderTests(SimpleTestCase):
"""ManageEventMixin must come before the generic view."""
def test_the_mixin_fetches_every_event(self):
for view in (views.EventUpdateView,
views.EventDeleteView,
views.EventCopyView):
with self.subTest(view.__name__):
self.assertIs(first_get_object(view),
views.ManageEventMixin)
class DeleteVerbTests(TestCase):
"""A DELETE request deletes nothing."""
def test_the_draft_stays_and_nothing_is_recorded(self):
sam = in_group('sam@example.org', 'Organizers')
draft = save_event(status=Event.Status.DRAFT)
draft.add_organizer(sam)
self.client.force_login(sam)
response = self.client.delete(
f'/events/{draft.pk}/delete/'
)
self.assertEqual(response.status_code, 405)
self.assertTrue(Event.objects.filter(
pk=draft.pk
).exists())
self.assertFalse(AuditEvent.objects.filter(
action=AuditEvent.Action.DELETE_EVENT
).exists())
first_get_object() walks a view’s MRO, skipping the view itself, and returns the first class that defines get_object(). vars(cls) holds only what that class defines itself, not what it inherits. For each of the three pages, that class must be ManageEventMixin: move the mixin after the generic view and this test fails. DeleteVerbTests sends Sam’s DELETE request to his own draft’s delete page and checks that the draft is still there and nothing was recorded. Run them:
Terminal
uv run python manage.py test events.tests.test_editing
Output
Found 2 test(s).
Creating test database for alias 'default'...
ERROR: test_the_mixin_fetches_every_event
AttributeError: module 'events.views' has no attribute
'EventDeleteView'. Did you mean: 'EventDetailView'?
Ran 2 tests in ...s
FAILED (errors=1)
The order test fails because the delete and copy views do not exist yet. The DELETE test already passes: the function’s require_http_methods refuses it. It is there so the class must keep that answer.
In events/views.py, the generic import gains the other three editing views:
and require_http_methods is no longer used in this file:
events/views.py
from django.views.decorators.http import require_POST
Replace event_create with:
events/views.py
class EventCreateView(LoginRequiredMixin, CreateView):
"""Create an event, for members who may add events.
dispatch() here runs before LoginRequiredMixin's, so it
lets visitors through to be sent to sign in, and refuses
a signed-in 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."""
user = request.user
if (user.is_authenticated
and not user.has_perm('events.add_event')):
deny(request, Action.CREATE_EVENT)
return super().dispatch(request, *args, **kwargs)
def form_valid(self, form):
"""Save the draft; its author becomes an organizer."""
with transaction.atomic():
event = form.save()
event.add_organizer(self.request.user)
record(self.request.user, Action.CREATE_EVENT,
event)
messages.success(self.request, 'Draft saved.')
return redirect(event)
The class defines its own dispatch(), and the class itself comes first in its MRO, so this dispatch() runs before LoginRequiredMixin’s. That is why it checks is_authenticated first: a visitor passes straight to super().dispatch(), where LoginRequiredMixin sends them to sign in. A signed-in member without add_event is refused with deny(), recorded, for every method, as before. form_valid() is the function’s POST branch.
Replace event_delete and event_copy with:
events/views.py
class EventDeleteView(LoginRequiredMixin, ManageEventMixin,
DeleteView):
"""Confirm, then delete a draft; or say why not.
Only GET and POST: DeleteView would answer DELETE by
calling Event.delete() directly, without form_valid(),
so without the draft rule and the record.
"""
template_name = 'events/delete.html'
manage_action = Action.DELETE_EVENT
http_method_names = ['get', 'post']
def get(self, request, *args, **kwargs):
"""Confirm a draft; send anything else back."""
self.object = self.get_object()
if self.object.status != Event.Status.DRAFT:
refuse(request, ValidationError(
'Only a draft can be deleted.'
))
return redirect(self.object)
return self.render_to_response(
self.get_context_data()
)
def form_valid(self, form):
"""Record, then delete the draft; or say why not."""
event = self.object
try:
with transaction.atomic():
# Recorded first: deleting clears event.pk.
record(self.request.user,
Action.DELETE_EVENT, event,
title=event.title)
event.delete_draft()
except ValidationError as error:
refuse(self.request, error)
return redirect(event)
messages.success(self.request, 'Draft deleted.')
return redirect('events:manage')
events/views.py
class EventCopyView(LoginRequiredMixin, ManageEventMixin,
FormView):
"""Ask for a start, then copy the event as a draft.
A FormView never calls get_object(), so get() and
post() fetch the event first; the method check still
comes before them, in dispatch().
"""
form_class = CopyForm
template_name = 'events/copy.html'
manage_action = Action.COPY_EVENT
http_method_names = ['get', 'post']
def get(self, request, *args, **kwargs):
"""Fetch the event, then show the form."""
self.object = self.get_object()
return super().get(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
"""Fetch the event, then check the form."""
self.object = self.get_object()
return super().post(request, *args, **kwargs)
def get_form_kwargs(self):
"""Give the form the event, for its default start."""
return super().get_form_kwargs() | {
'event': self.object
}
def get_context_data(self, **kwargs):
"""Add the event to the page."""
return super().get_context_data(**kwargs) | {
'event': self.object
}
def form_valid(self, form):
"""Copy the event as a draft, then open it to edit."""
with transaction.atomic():
copy = self.object.copy_as_draft(
self.request.user,
form.cleaned_data['starts_at'],
)
record(self.request.user, Action.COPY_EVENT,
copy, source=self.object.pk)
messages.success(self.request,
'Copied as a new draft.')
return redirect('events:edit', copy.pk)
EventDeleteView keeps both of the function’s refusals. GET for an event that is not a draft says so and goes back to the event, without a confirmation page. form_valid() records, then calls delete_draft(), which refuses a published event even if someone posts to the page directly. http_method_names = ['get', 'post'] is the line that matters most: without it, a DELETE request would reach DeletionMixin.delete(), which calls Event.delete() and skips both.
EventCopyView is a FormView, which has no object and never calls get_object(). So get() and post() call it first, then let FormView continue. get_form_kwargs() passes the event to CopyForm, which uses it for its starting values.
uv run python manage.py test events.tests.test_editing
Output
Found 2 test(s).
Creating test database for alias 'default'...
...
Ran 2 tests in ...s
OK
Step 7: Cancel a place, and the profile
The cancel page fetches a registration, not an event, so it has its own check: a member may cancel only their own place, and someone else’s is answered as if it were missing, recorded. In registrations/views.py, add DetailView to the generic import:
registrations/views.py
from django.views.generic import DetailView, ListView
and replace cancel_registration with:
registrations/views.py
class CancelRegistrationView(LoginRequiredMixin, DetailView):
"""Confirm, then cancel the member's own place.
get_object() answers someone else's place as if it were
missing, and records the attempt (Chapter 31).
"""
template_name = 'registrations/cancel.html'
pk_url_kwarg = 'registration_id'
http_method_names = ['get', 'post']
def get_queryset(self):
"""Places with their events, read in one query."""
return Registration.objects.select_related('event')
def get_object(self, queryset=None):
"""Return the place, or 404 if it is not theirs."""
registration = super().get_object(queryset)
if registration.member_id != self.request.user.pk:
deny(self.request, Action.CANCEL_REGISTRATION,
registration, hidden=True)
return registration
def get_context_data(self, **kwargs):
"""Add what the page says about the deadline."""
now = timezone.now()
event = self.object.event
deadline = event.cancellation_deadline
return super().get_context_data(**kwargs) | {
'registration': self.object,
'event': event,
'started': now >= event.starts_at,
'late': deadline is not None and now >= deadline,
}
def post(self, request, *args, **kwargs):
"""Cancel the place, then say what happened."""
registration = self.get_object()
try:
changed = registration.cancel(timezone.now())
except ValidationError as error:
messages.error(request, error.messages[0])
else:
say_cancelled(request, registration, changed)
return redirect('registrations:mine')
It is a DetailView with a post(): GET shows the confirmation, POST cancels. get_object() adds the ownership check where the place is fetched, as Chapter 36 did for the event page, so both GET and POST pass through it. pk_url_kwarg names the address’s registration_id. In registrations/urls.py:
The profile page needs no object from the address: it always edits the signed-in member’s own profile. Replace accounts/views.py with:
accounts/views.py
"""The accounts app's own views; allauth has the rest."""
from allauth.account.models import EmailAddress
from allauth.mfa.models import Authenticator
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import redirect
from django.views.generic import FormView
from .forms import ProfileForm
from .models import Profile
class ProfileView(LoginRequiredMixin, FormView):
"""Show the signed-in member's profile; no id is read."""
form_class = ProfileForm
template_name = 'accounts/profile.html'
http_method_names = ['get', 'post']
def get_initial(self):
"""Fill the form from the member and their profile."""
user = self.request.user
profile = Profile.of(user)
return {
'display_name': user.display_name,
'timezone': profile.timezone,
'phone': profile.phone,
}
def get_context_data(self, **kwargs):
"""Add the two-factor and email notes."""
user = self.request.user
return super().get_context_data(**kwargs) | {
'two_factor': Authenticator.objects.filter(
user=user, type=Authenticator.Type.TOTP,
).exists(),
'unconfirmed': EmailAddress.objects.filter(
user=user, verified=False,
).exists(),
}
def form_valid(self, form):
"""Save the profile, then show it again."""
form.save(self.request.user)
messages.success(self.request, 'Profile saved.')
return redirect('accounts:profile')
get_initial() fills the unbound form, as the function’s initial= did. A bound form ignores it. In accounts/urls.py:
Every failing row is one of two changes. First, LoginRequiredMixin runs before the method check, so a visitor now gets the sign-in page for every method, where the delete, copy, and cancel pages answered 405 first. Second, http_method_names = ['get', 'post'] now gives every page, for signed-in members too, 405 for HEAD, PUT, PATCH, DELETE, OPTIONS, and TRACE, where three of the functions answered every method with the page; and Raj’s PUT to Sam’s edit page is refused by method, not recorded. Neither change lets anyone do anything new. The first is also what Chapter 39’s sign-in-by-default middleware will do to every page. Accept both, and declare them. Replace the file with:
config/tests/test_editing_methods.py
"""How the six editing pages answer every method (37).
Written while they were functions; the rows that changed
when they became classes are declared in the tables.
"""
from datetime import timedelta
from django.test import TestCase
from django.utils import timezone
from config.helpers import answers, in_group, save_event
from registrations.models import Registration
from registrations.tests.test_registrations import verified
EVERY = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE',
'OPTIONS', 'TRACE']
SENT = ('GET', 'POST')
ONLY = '405 GET, POST'
# As classes (Chapter 37): sign-in first for every method;
# then GET and POST only, for everyone.
EDITING = [
(method, 'sign in', 'ok' if method in SENT else ONLY)
for method in EVERY
]
NOT_THEIRS = [
(method, 'sign in',
'403 recorded' if method in SENT else ONLY)
for method in EVERY
]
NO_ADD_PERMISSION = [
(method, 'sign in', '403 recorded') for method in EVERY
]
class EditingMethodTests(TestCase):
"""The editing pages' answers to each method, pinned."""
@classmethod
def setUpTestData(cls):
cls.sam = in_group('sam@example.org', 'Organizers')
cls.raj = in_group('raj@example.org', 'Organizers')
cls.sai = verified('sai@example.org')
cls.event = save_event(
starts_at=timezone.now() + timedelta(days=7)
)
cls.event.add_organizer(cls.sam)
save_event().add_organizer(cls.raj)
def check(self, path, member, table):
"""Compare the page's answers with each row."""
for method, signed_out, signed_in in table:
with self.subTest(path=path, method=method):
self.assertEqual(
answers(path, member, method),
(signed_out, signed_in),
)
def test_create(self):
self.check('/events/new/', self.sam, EDITING)
def test_create_without_permission(self):
self.check('/events/new/', self.sai, NO_ADD_PERMISSION)
def test_each_event_page_for_its_organizer(self):
for page in ('edit', 'delete', 'copy'):
self.check(f'/events/{self.event.pk}/{page}/',
self.sam, EDITING)
def test_each_event_page_for_another_organizer(self):
for page in ('edit', 'delete', 'copy'):
self.check(f'/events/{self.event.pk}/{page}/',
self.raj, NOT_THEIRS)
def test_cancel_registration(self):
place = Registration.objects.create(event=self.event,
member=self.sai)
self.check(f'/registrations/{place.pk}/cancel/',
self.sai, EDITING)
def test_profile(self):
self.check('/accounts/profile/', self.sai, EDITING)
Three tables now describe six pages: EDITING for the person the page is for, NOT_THEIRS for Raj on Sam’s event, and NO_ADD_PERMISSION, unchanged, for Sai on the new event page. Run everything:
Terminal
uv run python manage.py test --parallel
Output
Found 399 test(s).
Creating test database for alias 'default'...
...
Ran 399 tests in ...s
OK
Step 9: Groups, one action bar, and a danger area
The event form has eleven fields in one grid, in the model’s order. On a phone it is one long column; on a wide screen, the zone, the start, and the end are separated by the description. Group them as people think of them: what the event is, when it is, and how registration works. Create events/templates/events/event_fields.html:
Each fieldset is announced with its legend by a screen reader, so “Starts, group When” says which date a field is. as_field_group renders one field with Otahque’s field template, the same markup {{ form }} used. confirm_zone appears only when EventForm adds it, after a zone change. Use the include in events/templates/events/form.html:
events/templates/events/form.html
{% extends "base.html" %}
{% load static %}
{% block title %}New event | Otahque{% endblock %}
{% block content %}
<h1>New event</h1>
<p>Otahque saves it as a draft. Only its organizers and
the administrator can see it until it is published.</p>
<form method="post" class="card space-y-4 border
border-base-300 bg-base-100 p-6">
{% csrf_token %}
{% include "events/event_fields.html" %}
<div class="form-actions action-bar">
<button type="submit" class="btn btn-primary">
Save draft</button>
</div>
</form>
<script src="{% static 'otahque/event-zone.js' %}"
defer></script>
{% endblock %}
and in events/templates/events/edit.html, which also gains a danger area for drafts:
events/templates/events/edit.html
{% extends "base.html" %}
{% block title %}Edit {{ title }} | Otahque{% endblock %}
{% block content %}
<h1>Edit {{ title }}</h1>
{% if taken %}
<p class="rounded-box border border-base-content
px-3 py-1 text-sm">
Places taken: {{ taken }}. Otahque does not tell
members about changes yet.</p>
{% endif %}
<form method="post" class="card space-y-4 border
border-base-300 bg-base-100 p-6">
{% csrf_token %}
<input type="hidden" name="version"
value="{{ form.instance.version }}">
{% include "events/event_fields.html" %}
<div class="form-actions action-bar">
<button type="submit" class="btn btn-primary">
Save changes</button>
</div>
</form>
<p>
<a href="{{ event.get_absolute_url }}">
Back to the event</a>
</p>
{% if event.status == "draft" %}
<section class="danger-zone" aria-labelledby="danger">
<h2 id="danger">Delete this draft</h2>
<p>Deleting removes the draft and its organizer list.
It cannot be undone.</p>
<a class="btn btn-error btn-outline"
href="{% url 'events:delete' event.pk %}">
Delete draft</a>
</section>
{% endif %}
{% endblock %}
The delete page’s form becomes the same kind of area, events/templates/events/delete.html:
events/templates/events/delete.html
{% extends "base.html" %}
{% block title %}Delete {{ event.title }} |
Otahque{% endblock %}
{% block content %}
<h1>Delete {{ event.title }}?</h1>
<p>This draft and its organizer list will be removed. It
cannot be undone.</p>
<form method="post" class="danger-zone">
{% csrf_token %}
<button type="submit" class="btn btn-error">
Delete draft</button>
</form>
<p>
<a href="{{ event.get_absolute_url }}">Keep it</a>
</p>
{% endblock %}
Add the styles in static/otahque/source.css, inside @layer components, above .form-actions:
static/otahque/source.css
/* Editing pages (Chapter 37): a form in labelled
groups, one action bar below them, and a marked area
for what cannot be undone. */
.form-section {
padding-top: 1rem;
border-top: 1px solid var(--color-base-300);
}
.form-section:first-of-type {
padding-top: 0;
border-top: 0;
}
.form-section legend {
margin-bottom: 0.5rem;
font-size: 1.0625rem;
font-weight: 600;
}
.action-bar {
padding-top: 1rem;
border-top: 1px solid var(--color-base-300);
}
.danger-zone {
display: grid;
gap: 0.75rem;
justify-items: start;
margin-top: 2rem;
padding: 1rem 1.25rem;
border: 2px solid var(--color-error);
border-radius: var(--radius-box);
}
.danger-zone h2 {
font-size: 1.0625rem;
font-weight: 600;
}
Build the stylesheet and run the events tests, which check the form’s markup:
Terminal
npm run build
uv run python manage.py test events --parallel
Output
Found 215 test(s).
Creating test database for alias 'default'...
...
Ran 215 tests in ...s
OK
Open a draft’s edit page at a phone width and a desktop width, as in Figure 37.4.
Figure 37.4 — The edit page at 1280 and 390 pixels, after Step 9.
Step 10: Record what changed
ADR-004 decided where access rules live. Add a section at the end of docs/adr/ADR-004-access-rules.md:
docs/adr/ADR-004-access-rules.md
## Update, Chapter 37
The editing pages became classes. ManageEventMixin fetches
the event through event_to_manage(), so the rule is still
the Event methods and deny() (404 or 403, recorded). It is
written left of the generic view; a test checks that its
get_object() is the one each view uses. The option of
UserPassesTestMixin was compared in the chapter and not
used: it answers 403 for a hidden draft and records
nothing.
ADR-006 said that small one-off actions stay functions. The decision has changed: views become classes over time, each when a chapter next changes it. ADR-006 is not rewritten to look as if it always said so; a new section says what changed, when, and why. Add it at the end of docs/adr/ADR-006-views.md:
docs/adr/ADR-006-views.md
## Update, Chapter 37
Superseded in part by the user's decision of 24 November
2026: every view becomes a class over time, converted
when a chapter next changes it. "Small functions for
one-off actions" (option C) no longer describes the end
state; the views listed above as "stays" convert when a
chapter changes them.
Converted here, each after its method table:
- event_create became EventCreateView (CreateView); its
add_event check stays a recorded refusal, in dispatch().
- event_edit became EventUpdateView (UpdateView); post()
keeps save_edit(), so the form is checked on the
locked row (Chapter 33).
- event_delete became EventDeleteView (DeleteView) with
http_method_names = ['get', 'post']: DeleteView would
answer DELETE without form_valid().
- event_copy became EventCopyView (FormView).
- cancel_registration became CancelRegistrationView
(DetailView with post()).
- profile became ProfileView (FormView).
Rule 2 for editing views: LoginRequiredMixin first, then
ManageEventMixin, then the generic view, with
http_method_names = ['get', 'post']. A signed-out
visitor now gets the sign-in page for every method,
where the functions answered 405 first; the tables
declare it, and Chapter 39's middleware does the same.
Step 11: Check and commit
Terminal
uv run python check.py
Output
== python manage.py check
System check identified no issues (0 silenced).
== python manage.py makemigrations --check --dry-run
== python manage.py test --parallel
Found 399 test(s).
System check identified no issues (0 silenced).
Ran 399 tests in ...s
OK
== all checks passed
Terminal
git add .
git status --short
git commit -m "Turn the editing pages into classes"
Output
M accounts/urls.py
M accounts/views.py
A config/tests/test_editing_methods.py
M docs/adr/ADR-004-access-rules.md
M docs/adr/ADR-006-views.md
M events/templates/events/delete.html
M events/templates/events/edit.html
A events/templates/events/event_fields.html
M events/templates/events/form.html
A events/tests/test_editing.py
M events/urls.py
M events/views.py
M registrations/urls.py
M registrations/views.py
M static/otahque/site.css
M static/otahque/source.css
[main 1a2b3c4] Turn the editing pages into classes
16 files changed, 534 insertions(+), 144 deletions(-)
create mode 100644 config/tests/test_editing_methods.py
create mode 100644 events/templates/events/event_fields.html
create mode 100644 events/tests/test_editing.py
If something goes wrong
Table 37.3 — Recovery for Chapter 37
Symptom
Likely cause
Recovery
Raj can open Sam's edit page
ManageEventMixin written after the generic view
Put it left of the view; Step 6's order test names the view
A visitor gets 404 or 403 instead of the sign-in page
LoginRequiredMixin not first, or a dispatch() that checks before super()
Put LoginRequiredMixin first; check is_authenticated in your own dispatch()
NoReverseMatch for 'detail' with arguments ('',)
edit.html still uses event_id
Use event.get_absolute_url
ImproperlyConfigured: No URL to redirect to
form_valid() returned super().form_valid() without success_url
Return redirect(...) yourself, or set success_url with reverse_lazy()
A DELETE request deletes an event
http_method_names missing on a DeleteView
Add http_method_names = ['get', 'post']
BusyEditTests and EditVersionTests fail
post() removed from EventUpdateView
Restore post() with save_edit()
TemplateDoesNotExist: events/event_form.html
template_name missing
Add template_name
Anything else
A listing differs from yours
git diff shows your changes; git restore FILE returns a file to the last commit
Work through Table 37.4 from the folder that holds manage.py.
Table 37.4 — Verification checklist for Chapter 37
Check
Command or action
Expected result
Starting point
test --parallel
Found 391 test(s); OK
Tables first
test config.tests.test_editing_methods, after Step 2
Found 6 test(s); OK
The Custom Way
uv run python practice_mro.py
Wrong's get() uses View's get_object()
Mixin and edit page
test events --parallel, after Step 4
OK
Two other ways
test events.tests.test_compare
Found 3 test(s); OK
Order and DELETE tests first
test events.tests.test_editing, Step 6
FAILED, then OK
Tables after the change
test config.tests.test_editing_methods, Step 8
FAILED, then the declared tables
Everything
test --parallel, after Step 8
Found 399 test(s); OK
UI
New event and a draft's edit page at 390 and 1280 px
Three groups, one action bar, a red-bordered delete area; no sideways scroll
All checks
uv run python check.py
== all checks passed; Ran 399 tests
Commit
git log --oneline -1
Turn the editing pages into 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 36 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, with one sample draft added for the screenshots only and deleted afterwards.
Que. 1 Why does ManageEventMixin override get_object(), not dispatch() or get()?
Flip to check your answerFold answer back
Answer. get_object() is the one method every editing page calls to fetch the event, so the rule runs wherever the event is fetched, and only once. It also runs after dispatch() has checked the method, so a PUT is refused with 405 before the event is looked at.
Que. 2 class V(LoginRequiredMixin, UpdateView, ManageEventMixin): what does Raj get on Sam’s event, and why?
Flip to check your answerFold answer back
Answer. Sam’s edit form. Python looks for get_object() along the MRO from the left, and UpdateView’s parent SingleObjectMixin defines one before ManageEventMixin is reached. It fetches any event by number, so the rule never runs.
Que. 3 Why does EventDeleteView set http_method_names = ['get', 'post']?
Flip to check your answerFold answer back
Answer. A DELETE request would reach DeletionMixin.delete(), which calls the event’s delete() method directly, without form_valid(). That would skip the draft-only rule in delete_draft() and the record.
Que. 4 EventCreateView.dispatch() checks is_authenticated before has_perm(). What would a visitor get without that check?
Flip to check your answerFold answer back
Answer. 403. The class’s own dispatch() runs before LoginRequiredMixin’s, and a visitor has no permissions, so deny() would refuse them before the mixin could send them to sign in.
Que. 5 Option B answered 403 for Sam’s hidden draft. Why is that worse than 404?
Flip to check your answerFold answer back
Answer. It tells Raj that a draft with that number exists, which is exactly what “hidden” is meant to prevent. A 404 is the same answer a number that does not exist gets.
Mini-Challenge
The cancel page now answers only GET and POST. Write a test, in registrations/tests/test_cancel_verb.py, that a DELETE request from Sai to her own place’s cancel page gets 405 with Allow: GET, POST, and that her place is still active afterwards.
Hint:soon() and verified() in the registrations tests make an event and a member; self.client.delete() sends the request.
Model answer:
registrations/tests/test_cancel_verb.py
"""Mini-Challenge: a DELETE never cancels a place (37)."""
from django.test import TestCase
from registrations.models import Registration
from .test_registrations import soon, verified
class CancelVerbTests(TestCase):
"""The cancel page answers GET and POST only."""
def test_a_delete_request_cancels_nothing(self):
sai = verified('sai@example.org')
place = Registration.objects.create(event=soon(),
member=sai)
self.client.force_login(sai)
response = self.client.delete(
f'/registrations/{place.pk}/cancel/'
)
self.assertEqual(response.status_code, 405)
self.assertEqual(response['Allow'], 'GET, POST')
place.refresh_from_db()
self.assertEqual(place.status, 'active')
Output
Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...s
OK
It passes at once, because http_method_names already refuses DELETE. That is the point of the test: it keeps the answer if someone later removes the line. The model answer was run and then removed; the chapter’s checkpoint does not include it.
What We Learned
CreateView, UpdateView, DeleteView, and FormView show and check a form; form_valid() is where your saving goes.
The method resolution order decides which parent’s method runs; mixins go left of the generic view.
A mixin in the wrong place does nothing and fails no existing test; a test of the MRO catches it.
ManageEventMixin keeps the rule in Event methods and deny(): 404 for hidden, 403 otherwise, recorded.
UserPassesTestMixin is a different rule: always 403, never recorded.
Generic form views answer PUT, and DeleteView answers DELETE without form_valid(); http_method_names closes both.
Override the generic path where your project’s rules need it, as EventUpdateView.post() does for the lock.
Your own dispatch() runs before the mixins’ dispatch().
A changed decision is added to its ADR as a new section, not rewritten into the old one.
Key terms
Use Table 37.5 to explain this chapter’s ideas in your own words.
Table 37.5 — Key terms from Chapter 37
Term
Meaning
Generic editing view
A ready-made class for a form page: FormView, CreateView, UpdateView, DeleteView.
form_valid()
The hook that runs when a form is good; it saves and returns a response.
Mixin
A class that adds one ability to the classes that list it as a parent.
Access mixin
A mixin that decides who may use a view, such as LoginRequiredMixin.
Method resolution order (MRO)
The order Python searches a class and its parents for a method.
super()
Calls the next class's method in the MRO.
IDOR
Insecure direct object reference: reaching someone else's record by changing an id.
UserPassesTestMixin
Django's mixin that allows a request only if test_func() returns True.
http_method_names
The HTTP methods a class-based view answers.
Fieldset and legend
HTML's way to group form fields under a heading that is read with each field.
Danger area
A marked part of a page for actions that cannot be undone.
Readiness checkpoint: you are ready for Chapter 38 when uv run python check.py ends with “all checks passed” and 399 tests, Raj gets 404 for Sam’s draft and 403 for Sam’s published event on every editing page, the edit page shows three groups and, for a draft, the delete area, and git log --oneline -1 shows this chapter’s commit.
Git Commit
Your Chapter 37 work was committed once, in Step 11, as “Turn the editing pages into classes”: the table and the editing tests, ManageEventMixin and the six classes with their addresses, the form groups, the danger area, the styles, and the two ADR sections. If you kept the Mini-Challenge, commit it on its own:
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 bug hidden in a framework’s convenience and to choosing an authorization design 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 is get_object() for in an UpdateView?
What the interviewer is testing: Do you know where a generic view fetches its object, and so where a check belongs?
Flip to check your answerFold answer back
Perfect answer:get_object() fetches the one object the page works on. SingleObjectMixin’s version reads the primary key or slug from the address, using pk_url_kwarg for the name, filters get_queryset() by it, and raises 404 if nothing matches. UpdateView calls it in get() and post(), then gives the object to the form as its instance. Because every request to the page passes through it, it is the right place for a rule about who may see or change that object. Otahque’s ManageEventMixin replaces it with event_to_manage(), which fetches the event and refuses with 404 or 403, recorded.
Table 37.6 — Where each editing page fetches what it changes
Page
Fetches
Through
Edit, delete
The event
ManageEventMixin.get_object()
Copy
The event
ManageEventMixin.get_object(), called by get() and post()
Cancel a place
The registration
get_object(), with the ownership check
New event, profile
Nothing from the address
The signed-in member
Behind the scenes:
get_object() in Otahque's editing views
UpdateView.get() -> self.get_object()
ManageEventMixin.get_object()
event_to_manage(request, event_id, action)
hidden: deny(..., hidden=True) -> 404, recorded
not theirs: deny(...) -> 403, recorded
Checking access in get() only, so post() saves for anyone.
Calling get_object() twice, once in a check and once to fetch, as test_func() often does.
Follow-up the interviewer might ask:
Why does ManageEventMixin.get_object() not call super()? (There is no other way to fetch an event that a view should fall back to; falling back would skip the rule.)
What does self.kwargs hold? (The values from the address pattern, such as event_id.)
L2 (Mid-Level): Predict what happens when the access mixin is written after UpdateView
What the interviewer is testing: Can you reason about the MRO before running anything?
Flip to check your answerFold answer back
Perfect answer: Python searches the class, then its parents in the order listed, then their parents. With UpdateView listed before ManageEventMixin, the search reaches SingleObjectMixin, one of UpdateView’s parents, before the mixin. SingleObjectMixin.get_object() fetches any event by number, so the page works for anyone signed in: Raj gets Sam’s form, and nothing is recorded. No test that existed before this chapter fails, because the page still works for Sam. Otahque’s order test walks each view’s MRO and fails if the first get_object() after the view is not the mixin’s.
Figure 37.5 — The access mixin in the wrong place.
Behind the scenes:
The MRO of the wrong order (shortened)
V, LoginRequiredMixin, ..., UpdateView, ...,
SingleObjectMixin <- get_object() found here
..., ManageEventMixin <- never reached
Code proof: the positions of the two classes in the wrong order’s MRO, and whose method wins:
Output
7 11
get_object() from SingleObjectMixin
Common mistakes:
Believing the order of parents only matters for dispatch().
Writing a mixin’s method so it calls super() and then ignores the result.
Follow-up the interviewer might ask:
Would LoginRequiredMixin still work in the wrong order? (Yes: it overrides dispatch(), and nothing before it defines one; only get_object() is shadowed.)
How else could you guard against this? (A system check or a base class that fixes the order; Otahque’s test is the simplest.)
L3 (Senior): Defend 404 for a hidden event and 403 for a visible one
What the interviewer is testing: Can you explain an authorization answer as a decision about information?
Flip to check your answerFold answer back
Perfect answer: A refusal is information. 403 says “this exists, and you may not”. For an event anyone can see on the public list, that leaks nothing, and it tells Raj honestly why he is refused. For a draft, the fact that it exists, or its number, is exactly what is hidden, so the answer must be the one a missing number gets: 404. Both are recorded, because the administrator wants to know about the attempt either way; the record is for us, not for the person refused. UserPassesTestMixin cannot make that distinction, because its test answers only yes or no; deny() takes hidden= from the rule that knows.
Figure 37.6 — Why a hidden event gets 404.
Behind the scenes:
deny(request, action, event, hidden)
signed in: record the refused attempt
hidden: raise Http404
else: raise PermissionDenied (403)
Code proof:deny() for a hidden event and a visible one:
Output
hidden Http404
visible PermissionDenied
Common mistakes:
Returning 403 for everything, because “it is more honest”.
Recording nothing for a 404, so probing for hidden numbers leaves no trace.
Follow-up the interviewer might ask:
Does a 405 to Raj’s PUT leak anything? (No: it is the same for every number, existing or not.)
What would an API return? (The same rule; Chapter 50 reuses the Event methods.)
L4 (Staff): A DELETE request deleted a published event. Diagnose it
What the interviewer is testing: Can you find a path through a framework that skips your own code?
Flip to check your answerFold answer back
Perfect answer: Since Django 4.0, DeleteView handles POST through a form: post() calls form_valid(), where a project puts its rules, as Otahque’s does with delete_draft() and the record. But DeleteView also inherits delete() from DeletionMixin, which answers the HTTP DELETE method by fetching the object and calling its delete() method directly. No form, no form_valid(), no rule. A browser form never sends DELETE, but a script can, with a valid CSRF token, so an organizer could delete a published event and leave no record. In Otahque the database refused, because organizer assignments are protected, which turned it into a 500 error; in a project without that, the event would be gone. The fix is http_method_names = ['get', 'post'], and a test that a DELETE request deletes nothing.
Figure 37.7 — How a DELETE request skips form_valid().
Behind the scenes:
DeleteView, by method
GET get() confirmation page
POST post() -> form_valid() your rules
DELETE DeletionMixin.delete() -> object.delete()
Code proof: the two lines of DeletionMixin.delete() that matter, and what Otahque’s page answers:
Putting the rule in form_valid() and assuming every deletion passes through it.
Testing only what a browser sends.
Follow-up the interviewer might ask:
Why did Django keep delete()? (Backward compatibility: before 4.0, POST called it too.)
Where else could the rule live so no path skips it? (In the model: Event.delete() itself could refuse anything that is not a draft. That would also bind the shell and the admin, which may be what you want; it is a decision to record, not a side effect.)
L5 (Lead): Your team wants PermissionRequiredMixin with object permissions. Defend not using it
What the interviewer is testing: Can you weigh a framework’s standard tool against a rule it cannot express?
Flip to check your answerFold answer back
Perfect answer: Django’s permission system answers “may this person do this kind of thing”, and with an object argument, “to this thing”. But Django’s ModelBackend does not check objects at all, and User.has_perm() returns True for any active superuser before a backend is asked. So has_perm('events.change_event', event) is True for every superuser, for every event, whatever Otahque’s organizer rule says. To use object permissions we would need a third-party backend that stores a permission per event, and we already store that fact as OrganizerAssignment. Chapter 30 chose rules as Event methods; one mixin calls them on every page, and Chapter 50’s API permission classes will call the same methods. One rule, one place, tested once.
Figure 37.8 — Why Otahque does not use object permissions.
Table 37.7 — Object permissions and Event methods
Question
Object permissions
Event methods
Who decides
A backend, per stored permission
Event.can_be_edited_by()
Superuser
Always allowed
Only if they organize it
Stored as
Permission rows per object
OrganizerAssignment, already there
Hidden draft
403
404, recorded
Reused by the API
With the same backend
Called by permission classes (50)
Behind the scenes:
User.has_perm(perm, obj)
active superuser -> True, no backend asked
else each backend's has_perm(user, perm, obj)
ModelBackend ignores obj (returns False for objects)
Code proof:has_perm() with an event, for a superuser who organizes nothing:
Output
has_perm with any event: True
Common mistakes:
Granting superuser to organizers “to make it work”.
Duplicating organizer rows as permission rows that can drift apart.
Follow-up the interviewer might ask:
When would object permissions be right? (When permissions are granted per object by people, as in a document-sharing app, and stored nowhere else.)
How would you let administrators edit any event? (Make it part of the rule in can_be_edited_by(), named and tested, not a side effect of is_superuser.)