Chapter 48 · DRF serializers and validationCHAPTER 48
Complete six-part pre-release for review. One package: djangorestframework 3.18.3. The edit page's saving moves into Event.edit(), which the API shares. Publishing and cancelling now make a new version. Three earlier tests change on purpose (declared in the chapter).
Working towards: API and integrations (Chapter 54). Another program can list published events through an API and receive signed notifications when an event changes. All milestones
CHAPTER FORTY-EIGHT
DRF serializers and validation
Stage 6: APIs and real-time updates (Chapters 47 to 54)
Prerequisites: Chapters 9 to 47, including the Chapter 47 project with its 645 passing tests, the API contract and its tests, the edit page with its version check (Chapter 33) and its questions (Chapter 38), the audit trail (Chapter 30), change emails (Chapters 43 and 44), and promotion from the waitlist (Chapter 46)
What you’ll build: Django REST framework, configured to refuse by default; the public reads rebuilt with serializers, against Chapter 47’s unchanged tests; one edit path that the edit page and the API share; the organizer’s own events, where a program creates drafts and changes them with If-Match; refusals by name for fields that may not be set; times that must carry an offset; a dry run that says what a change would do; and, on the edit page, every error listed at the top
Why This Matters
Sam keeps his clinic’s details in a file on his laptop. When the room changes, he edits the file, then copies the change into Otahque’s edit page by hand, and once he forgot the time zone. He would rather run a script that does it; and the AI agent he works with could draft next month’s clinic for him to check. Chapter 47 wrote down how that will work: /api/v1/my/events/, an ETag, If-Match, a dry run. This chapter builds it.
A write is where an API can do damage. A program can send a field the edit page never shows, such as "status": "published", and publish a draft that is not ready. It can send 17:30 without saying in which zone, and Otahque has to guess. It can send a change based on an old copy, and undo what Raj saved a minute ago. And if the API saves an event its own way, it skips everything the edit page does after saving: the audit record, the waiting members promoted when the capacity rises, the emails to members when the place changes.
So a write through the API must follow exactly the site’s rules, by the same code. This chapter replaces Chapter 47’s hand-written views with Django REST framework (DRF), whose serializers check what a program sends the way forms check what a person types, and moves the edit page’s saving into one method on the event that both doors call.
By the end of the chapter, you will be able to:
explain what DRF adds to Django, and configure its defaults so that nothing is open by accident;
write serializers that turn events into JSON and check what clients send;
refuse fields a client may not set, by name, instead of dropping them silently;
require times with an offset, and say why guessing a zone is wrong;
share one edit path between a page and an API, so the rules and side effects cannot drift apart;
protect a write with If-Match, 412, and 428;
offer a dry run that reports what a write would do without doing it;
list a form’s errors at the top of the page, each linked to its field.
Out of scope: tokens for programs (Chapter 50), the list of my events, publish, cancel, and delete (Chapter 49), paging and filtering (Chapter 51), and registering members through the API (not planned).
What problem exists? Chapter 47 wrote JSON views by hand: the fields one by one, the errors, the methods allowed, content negotiation. Writes would need much more: reading JSON, checking each field, reporting errors per field.
What did people do before? Exactly what Chapter 47 did, view after view, each slightly different.
What is it?Django REST framework (DRF) is a package of tools for APIs on Django: views that read and write JSON, serializers that convert and check data, authentication and permission classes, and content negotiation. Version 3.18.3 (October 2026) supports Django 6.1, and 3.18.2 fixed three security problems, so 3.18.3 is the floor.
Why use it? It is the most used way to build APIs on Django, its serializers work like the forms you know, and its pieces replace hand-written code with tested code.
Now let’s use it. Step 2 installs it, with defaults stricter than its own.
DRF’s defaults suit a quick start, not Otahque. The probe for this chapter showed what they do here (Table 48.1).
Table 48.1 — DRF’s defaults, and Otahque’s
Setting
DRF's default
Otahque (Step 2)
Who may call a view
AllowAny: anyone
IsAuthenticated, unless a view says AllowAny
How callers sign in
Session and Basic
Session only; tokens in Chapter 50
What it reads
JSON, forms, files
JSON only
What it answers
JSON, and a browsable HTML page
JSON only (the page returns in Chapter 49)
How errors look
{"detail": "..."}
Problem details, through Otahque's handler
Under the Hood: why DRF’s views skip Otahque’s sign-in rule
Since Chapter 39, LoginRequiredMiddleware sends anyone not signed in to the sign-in page, unless the view is marked login_not_required. A redirect to an HTML page is useless to a program, so DRF opts its views out: APIView.as_view() sets login_required = False on every view it makes. DRF’s own rule then decides, and its default is AllowAny. So a DRF view written without thinking is open to everyone, even in a project that is closed by default. And with Basic authentication on, DRF’s other default, a member’s email and password work against the API directly, with no two-factor step and none of allauth’s limits on wrong guesses: the probe for this chapter signed in that way. That is why Step 2 sets the defaults before any DRF view exists, and why Chapter 39’s guard test learns DRF’s rule in Step 7.
Serializers: the API’s forms
New Concept: a serializer
What problem exists? An API needs to turn an event into JSON, and JSON from a client into checked values for an event, field by field, with errors a client can act on.
What did people do before? Built dictionaries by hand, as event_data() did in Chapter 47, and checked each incoming value by hand.
What is it? A serializer is a class that does both directions. to_representation() turns an object into simple data for JSON; is_valid() checks incoming data, field by field and then as a whole in validate(), and leaves the clean values in validated_data. A ModelSerializer builds its fields from a model, as a ModelForm does.
Why use it? One class per shape of data, with the conversion and the checks together, and errors already per field.
Now let’s use it. Step 3 writes EventSerializer, which sends exactly what Chapter 47’s views sent.
The two directions are drawn in Figure 48.1.
Figure 48.1 — A serializer, reading and writing.
Fields a client may not set
The quickest serializer, in many tutorials, is fields = '__all__': every field of the model. For writes, that is how an API gets overposting (also called mass assignment): a client sends a field the developer never meant to accept, and the serializer accepts it. Step 6 tries it on Otahque’s events: "status": "published" is accepted, so a draft that is not ready would be published, without the checks publish() makes.
The fix is a list of what may be written, and nothing else. DRF then has a second habit that hides mistakes: a field it does not know is dropped silently. A script that sends "tittle" instead of "title" gets a 200 and no change, and nobody notices. Otahque’s write serializer refuses both kinds by name, as Table 48.2 shows (D48.1).
Table 48.2 — What a write may send
Field
Example
Answer
One of the ten writable fields
"location": "Room 2"
Checked, then saved
A field the API shows but nobody may set
"status": "published"
422: cannot be set through the API
A field events do not have
"tittle": "..."
422: no field with this name
One rule, two doors
The edit page checks an event with its form and the model; the API checks it with a serializer. If the rules are written twice, they drift: the probe for this chapter showed a plain ModelSerializer saving an event that ends before it starts, which the database then refused with a crash, a 500. The rules belong to the model, as Event.clean() and its constraints, and full_clean() runs them all; the serializer calls it, as the form does (D48.2).
Saving has the same problem in a bigger form. After the edit page saves, Chapter 33’s save_edit() does five more things: it takes the event’s lock and checks the version, records the edit (Chapter 30), gives new places to waiting members (Chapter 46), and queues emails to members about a new time or place (Chapters 43 and 44). An API that saves the serializer would skip all five. So Step 5 moves them from the view into a method on the event, Event.edit(), which both doors call; each door only reads its own input (N48.5). Figure 48.2 shows the result.
Figure 48.2 — One edit path, two doors.
Times with an offset
A person typing into the edit page types a local time, and the page reads it in the event’s zone, with Chapter 24’s checks for clock changes. A program sends text, and "2026-12-05T17:30:00" says nothing about where. DRF’s answer is to read it in the active zone, and Otahque activates the viewer’s own zone (Chapter 23). The probe for this chapter showed the result: 17:30 meant for a London event, sent by a member whose profile says Kolkata, was stored as 12:00 UTC, five and a half hours wrong, with a 200.
A time with an offset, 17:30:00Z or 17:30:00+05:30 (RFC 3339), names one instant, wherever it is read. So Otahque’s API requires one, and refuses a time without, by name (N48.4). The zone still matters for showing times to people, so changing timezone must come with the times it moves, in the same request (N48.6), the API’s form of the edit page’s confirmation.
Writes that cannot lose a change
New Concept: If-Match, 412, and 428
What problem exists? Sam’s script reads the event, Raj changes the capacity on the site, then the script saves its copy and undoes Raj’s change without anyone knowing: the “lost update” of Chapter 25.
What did people do before? Last save wins, or a lock held while a person types, which nobody can afford.
What is it? The client sends back the ETag it read in an If-Match header. The server compares it with the resource’s current tag, strongly (RFC 9110): equal, and the write goes ahead; different, and the answer is 412 Precondition Failed, with nothing saved. A server may require the header, and answer 428 Precondition Required (RFC 6585) when it is missing.
Why use it? It is the edit page’s version check, in HTTP, for programs.
Now let’s use it. The organizer’s view of an event carries ETag: "v{version}", and Step 7’s PATCH requires it.
"v{version}" works as a tag only if every change to what the organizer’s view shows makes a new version. Edits already do. Publishing and cancelling change the status, which that view shows, so from this chapter they make a new version too. The public reads keep Chapter 47’s tag from the body, because places and organizers still change without a version.
Ask before you act
A program, and especially an AI agent acting for a person, should be able to say “this is what will happen” before it happens. A dry run is a request that goes through every check and every step of a write, then undoes it all and reports the result. Otahque’s is ?dry_run=true: Event.edit() runs inside its transaction as usual, notes what it changed, how many waiting members it promoted, and how many emails it queued, then rolls the transaction back. Because it is the same code, a dry run cannot disagree with the real write. Figure 48.3 shows an agent using it.
Figure 48.3 — A dry run, then the write.
In practice: what an agent needs from an API
Situation. An organizer asks an AI agent to “move next week’s clinic to Room 2 and add ten places”.
Application. The agent reads the contract’s OpenAPI file to find changeMyEvent, reads the event and its ETag, sends the change with ?dry_run=true, shows the organizer the effects (ten places, two waiting members promoted, emails to the people holding places), and only then sends the write with If-Match. Errors come back as problem details naming each field, which the agent can fix without guessing.
Consideration. None of this trusts the agent. The server checks every field, every rule, and the version, whoever sends the request; and from Chapter 50, the agent’s token can be limited to the actions it was given. An agent is only as safe as the API it uses.
Start from Chapter 47, in the folder containing manage.py, with Otahque on PostgreSQL 18, 645 passing tests, and the work committed (the last commit is “Publish events through an API”). One package is added, djangorestframework 3.18.3. There is no migration. The new files are the serializers, two test modules, and a template for the error summary. The settings, the API’s problems, views, and addresses, the events models and views, the contract and its OpenAPI file, the developers page, the edit page, the stylesheet, and three earlier test modules change. The visible result: the public reads answer exactly as before, now from DRF; an organizer’s program creates drafts and changes its events at /api/v1/my/events/, by the site’s rules and with the site’s side effects, safe from lost updates, with a dry run; and the edit page lists its errors at the top. The commands were checked in Windows PowerShell 5.1 and Git Bash against PostgreSQL 18.
The Custom Way
Chapter 47 was the Custom Way for reading. For writing, the Custom Way is the quick serializer a tutorial would show, fields = '__all__', and Step 6 runs it against Otahque’s events to see what it accepts. It is short, and it is wrong for writes, in a way that only a test or an attacker notices.
The Django Way
The Django Way here is DRF with its defaults set on purpose, serializers that list what they take, and the rules and side effects left where they belong: on the model, in one method both doors call.
Step 1: Check the starting point
Terminal
uv run python manage.py test --parallel
Output
Found 645 test(s).
Creating test database for alias 'default'...
...
Ran 645 tests in ...s
OK
Terminal
git status --short
git log --oneline -1
Output
... Publish events through an API
Step 2: Install DRF, strict from the start
Terminal
uv add djangorestframework==3.18.3
Output
Resolved 53 packages in ...
Installed 1 package in ...
+ djangorestframework==3.18.3
# Django REST framework (Chapter 48, N48.7). DRF's views
# opt out of LoginRequiredMiddleware (Chapter 39) and use
# these defaults instead, so they must be as strict: only
# the session (Basic, DRF's other default, would take a
# password with no two-factor step), signed in unless a
# view says AllowAny, JSON in and out, errors as problem
# details. Chapter 50 adds tokens for programs.
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.SessionAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
'DEFAULT_RENDERER_CLASSES': [
'rest_framework.renderers.JSONRenderer',
],
'DEFAULT_PARSER_CLASSES': [
'rest_framework.parsers.JSONParser',
],
'EXCEPTION_HANDLER': 'api.problems.exception_handler',
}
EXCEPTION_HANDLER names a function Step 4 writes; DRF imports it only when an error happens, so the project still starts:
Terminal
uv run python manage.py check
Output
System check identified no issues (0 silenced).
Step 3: The read serializer
Create api/serializers.py:
api/serializers.py
"""Events in and out of the API, with DRF (Chapter 48).
A serializer is to the API what a form is to a page: it
turns an event into the contract's fields, and checks and
converts what a client sends. The rules themselves stay on
the model, which full_clean() runs, as the edit page does.
"""
from datetime import UTC
from django.db import models
from rest_framework import serializers
from events.models import Event
from .representation import absolute
class UTCDateTimeField(serializers.DateTimeField):
"""A time sent in UTC, ending in Z, whoever asks.
DRF would show times in the active zone, which Otahque
sets to the viewer's own (Chapter 23).
"""
def __init__(self, **kwargs):
"""Use UTC, not the viewer's zone."""
super().__init__(default_timezone=UTC, **kwargs)
# ModelSerializer picks a serializer field for each model
# field from this table; times get Otahque's own.
UTC_MAPPING = {
**serializers.ModelSerializer.serializer_field_mapping,
models.DateTimeField: UTCDateTimeField,
}
class EventSerializer(serializers.ModelSerializer):
"""An event as the public API shows it (Chapter 47)."""
serializer_field_mapping = UTC_MAPPING
places_left = serializers.SerializerMethodField()
organizers = serializers.SerializerMethodField()
cover = serializers.SerializerMethodField()
url = serializers.SerializerMethodField()
class Meta:
model = Event
fields = [
'id', 'title', 'description', 'starts_at',
'ends_at', 'timezone', 'location', 'status',
'capacity', 'places_left',
'registration_opens_at',
'registration_closes_at',
'cancellation_deadline', 'organizers', 'cover',
'url',
]
def get_places_left(self, event):
"""Return the places left, never below 0."""
return max(event.places_left, 0)
def get_organizers(self, event):
"""Return the current organizers' display names."""
return [assignment.member.display_name
for assignment in event.current_organizers]
def get_cover(self, event):
"""Return the cover's full address, or None."""
return absolute(event.cover.url) if event.cover else None
def get_url(self, event):
"""Return the full address of the event's page."""
return absolute(event.get_absolute_url())
ModelSerializer builds a serializer field for each model field it lists, choosing the kind from serializer_field_mapping. Otahque’s table differs in one entry: times become UTCDateTimeField, because DRF’s own DateTimeField writes a time in the active zone, which Otahque sets to the viewer’s. The four computed fields are SerializerMethodFields, each read from the method named get_ and the field.
Step 4: Problems, and the public reads with DRF
DRF’s errors need to become problem details too. api/problems.py becomes:
api/problems.py
"""Errors as problem details (RFC 9457), not HTML pages.
A client reads the status code first, then this body: a
title for the kind of problem, a detail for this time.
Since Chapter 48, DRF's errors come here too, through
exception_handler().
"""
from http import HTTPStatus
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.core.exceptions import (
ValidationError as ModelError,
)
from django.http import Http404, JsonResponse
from rest_framework import exceptions, status, views
from rest_framework.serializers import as_serializer_error
PROBLEM = 'application/problem+json'
# The status phrases RFC 9110 gives each code: with type
# about:blank, the title is the phrase (RFC 9457 4.2.1).
TITLES = {
404: 'Not Found',
405: 'Method Not Allowed',
406: 'Not Acceptable',
}
def problem(status, detail, **extra):
"""Return a problem-details response for status."""
body = {'type': 'about:blank', 'title': TITLES[status],
'status': status, 'detail': detail, **extra}
return JsonResponse(body, status=status,
content_type=PROBLEM)
class PreconditionRequired(exceptions.APIException):
"""A write without If-Match (RFC 6585: 428)."""
status_code = status.HTTP_428_PRECONDITION_REQUIRED
default_detail = ('Send the ETag you read in If-Match, '
'so a change made since is not lost.')
class PreconditionFailed(exceptions.APIException):
"""A write with an old ETag (RFC 9110: 412)."""
status_code = status.HTTP_412_PRECONDITION_FAILED
default_detail = ('The event changed after you read '
'it. Read it again, then send its new '
'ETag in If-Match.')
def pointers(errors, prefix='#'):
"""Turn DRF's error dictionary into RFC 9457's list.
Each item names the field with a JSON Pointer, such as
#/capacity; errors about the whole request point at #.
"""
found = []
for name, messages in errors.items():
if isinstance(messages, str):
messages = [messages]
where = prefix
if name not in ('non_field_errors', '__all__'):
where = f'{prefix}/{name}'
for message in messages:
found.append({'pointer': where,
'detail': str(message)})
return found
def detail_of(exc, request):
"""Return the detail to show, in Otahque's words."""
if isinstance(exc, exceptions.MethodNotAllowed):
return f'{request.method} is not allowed here.'
if isinstance(exc, exceptions.NotAcceptable):
return 'This address answers only in application/json.'
return str(exc.detail)
def exception_handler(exc, context):
"""Answer every error in a DRF view as problem details.
Django's own errors, from the views the site and the
API share, become DRF's first: Http404, PermissionDenied,
and a model's ValidationError, from full_clean(). Then
DRF's handler makes the response, and this rewrites its
body. Every invalid request is 422 Unprocessable
Content, with a list of errors.
"""
if isinstance(exc, Http404):
exc = exceptions.NotFound()
elif isinstance(exc, PermissionDenied):
exc = exceptions.PermissionDenied()
elif isinstance(exc, ModelError):
exc = exceptions.ValidationError(
as_serializer_error(exc))
response = views.exception_handler(exc, context)
if response is None:
return None
request = context['request']
if isinstance(exc, exceptions.ValidationError):
errors = exc.detail
if not isinstance(errors, dict):
errors = {'__all__': errors}
response.status_code = 422
response.data = {
'type': f'{settings.SITE_URL}/developers/#invalid',
'title': 'Invalid fields',
'status': 422,
'detail': 'Some fields are invalid; see errors.',
'errors': pointers(errors),
}
else:
code = response.status_code
response.data = {
'type': 'about:blank',
'title': HTTPStatus(code).phrase,
'status': code,
'detail': detail_of(exc, request),
}
response.content_type = PROBLEM
return response
exception_handler() lets DRF build its usual response, then replaces the body. Django’s own exceptions, which the views shared with the site raise, are turned into DRF’s first. Invalid data gets status 422 Unprocessable Content and the errors list from RFC 9457’s example, one item per problem, each pointing at its field with a JSON Pointer such as #/capacity. Its type is a link to the developers page, where Step 8 explains it. PreconditionRequired and PreconditionFailed are the 428 and 412 answers, as DRF exceptions.
Then api/views.py becomes:
api/views.py
"""The API's views (Chapters 47 and 48).
The public reads, written by hand in Chapter 47, are DRF
generic views since Chapter 48, with the same answers.
"""
from django.conf import settings
from django.contrib.auth.decorators import login_not_required
from django.http import FileResponse
from django.middleware.http import ConditionalGetMiddleware
from django.shortcuts import render
from django.urls import reverse
from django.utils.cache import patch_cache_control
from django.utils.decorators import decorator_from_middleware
from django.views.decorators.http import require_safe
from rest_framework import exceptions, generics
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from .problems import problem
from .representation import absolute, listed, upcoming
from .serializers import EventSerializer
# Adds an ETag made from the body, and answers a matching
# If-None-Match with 304 Not Modified and no body.
conditional = decorator_from_middleware(
ConditionalGetMiddleware)
class PublicRead(generics.GenericAPIView):
"""A public read: GET and HEAD only, revalidated.
AllowAny is said here, on purpose: DRF's default, set
in the settings, is to refuse anyone not signed in.
"""
permission_classes = [AllowAny]
serializer_class = EventSerializer
http_method_names = ['get', 'head']
def finalize_response(self, request, response, *args,
**kwargs):
"""Ask clients to revalidate a stored copy."""
patch_cache_control(response, no_cache=True)
return super().finalize_response(
request, response, *args, **kwargs)
class EventList(PublicRead):
"""Published and cancelled events not yet ended."""
def get(self, request):
"""Send the list, as {"results": [...]}."""
events = self.get_serializer(upcoming(), many=True)
return Response({'results': events.data})
class EventDetail(PublicRead):
"""One published or cancelled event, or 404."""
def get(self, request, event_id):
"""Send the event, or a problem 404."""
event = listed().filter(pk=event_id).first()
if event is None:
raise exceptions.NotFound(
'No published event has this id.')
return Response(self.get_serializer(event).data)
event_list = conditional(EventList.as_view())
event_detail = conditional(EventDetail.as_view())
@login_not_required
@require_safe
def openapi(request):
"""Send the contract for programs, openapi.yaml."""
path = settings.BASE_DIR / 'docs/api/openapi.yaml'
response = FileResponse(open(path, 'rb'),
content_type='application/yaml')
patch_cache_control(response, no_cache=True)
return response
@login_not_required
def not_found(request, rest):
"""Answer any other address under /api/v1/ with 404."""
return problem(404, 'No such address. Addresses end '
'with a slash, as /api/v1/events/ does.')
@login_not_required
@require_safe
def developers(request):
"""Show the page for people who write programs."""
events = absolute(reverse('api:event_list'))
return render(request, 'api/developers.html', {
'example': f'curl {events}',
})
PublicRead holds what the two reads share: AllowAny, written here on purpose since the default now refuses visitors; only GET and HEAD; and no-cache, added in finalize_response(), the hook every DRF response passes through. conditional still wraps the finished view, and works on DRF’s responses too: they are rendered later, and the decorator waits for that. openapi, not_found, and developers stay plain Django views.
The contract’s tests, unchanged since Chapter 47, are the proof that nothing a client sees has moved:
Terminal
uv run python manage.py test api
Output
Found 25 test(s).
Creating test database for alias 'default'...
...
Ran 25 tests in ...s
OK
Step 5: One edit path
In events/models.py, below the django.db import:
events/models.py
from django.forms.models import model_to_dict
above EventQuerySet:
events/models.py
class StaleEdit(Exception):
"""The event changed after the editor read it (33, 48)."""
class Edit:
"""What Event.edit() did, or, in a dry run, would do."""
def __init__(self, event, changed, promoted, emails):
"""Keep the event and the edit's effects."""
self.event = event
self.changed = changed
self.promoted = promoted
self.emails = emails
and above delete_draft(), two methods:
events/models.py
def save_draft(self, by, dry_run=False):
"""Save this new event as a draft; by organizes it.
The edit page and the API both create events here
(Chapter 48): checked as the model's rules say,
saved, its author made its first organizer, and the
creation recorded, together. A dry run checks and
saves, then undoes it all.
"""
self.status = self.Status.DRAFT
self.full_clean()
with transaction.atomic():
self.save()
self.add_organizer(by)
record(by, AuditEvent.Action.CREATE_EVENT, self)
if dry_run:
transaction.set_rollback(True)
return self
def edit(self, by, version, change, dry_run=False):
"""Change this event under its lock; return an Edit.
version is the one the editor read: any other raises
StaleEdit, and nothing changes. change(event) gets
the locked copy, sets its new values, may save rows
that belong to it, and returns the names of anything
else it changed; it raises ValidationError to change
nothing. Then, as one transaction: a new version is
saved, the edit recorded (30), waiting members given
new places (46), and holders told of a new time or
place (43). The edit page and the API both call it
(Chapter 48). A dry run does it all, then undoes it.
"""
# Imported here: emails imports tasks, which imports
# this module.
from . import emails
with transaction.atomic():
event = self.locked()
if version != event.version:
raise StaleEdit
before = model_to_dict(event)
extra = change(event)
event.version += 1
event.save()
after = model_to_dict(event)
changed = [name for name in after
if before[name] != after[name]]
changed += extra
record(by, AuditEvent.Action.EDIT_EVENT, event,
fields=changed)
queued = event.deliveries.count()
promoted = event.fill_from_waitlist(timezone.now())
told = [name for name in changed
if name in emails.TOLD]
if told and event.status == self.Status.PUBLISHED:
emails.event_changed(event, told)
queued = event.deliveries.count() - queued
if dry_run:
transaction.set_rollback(True)
return Edit(event, changed, promoted, queued)
edit() is Chapter 33’s save_edit() without the form. The caller passes the version it read and a function, change, that sets the new values on the locked copy and may save rows that belong to the event; everything after is the same for every caller. save_draft() is the same idea for a new event. Both take dry_run: transaction.set_rollback(True) marks the transaction to be undone when its block ends, so a dry run goes through every step and keeps none of them.
Publishing and cancelling now count as versions, so an organizer’s If-Match read before them is refused. In publish(), the lines that save the status become:
events/models.py
event.status = self.Status.PUBLISHED
# Chapter 48: a new version, as an edit is, so an
# organizer's If-Match from before is refused.
event.version += 1
event.save(update_fields=['status', 'version'])
self.status, self.version = event.status, event.version
def form_valid(self, form):
"""Save the draft; its author becomes an organizer."""
event = form.save(commit=False)
event.save_draft(self.request.user)
messages.success(self.request, 'Draft saved.')
return redirect(event)
and save_edit() becomes:
events/views.py
def save_edit(request, event):
"""Save the edit form and the questions, through edit().
Return None once saved, or the form and the question
formset to show again. Event.edit() holds the lock and
the version check, records the edit, promotes waiting
members, and queues the emails (Chapter 48); this page
only reads the form. Event and questions are saved
together, or neither is (Chapter 38).
"""
shown = {}
def change(locked):
"""Read the form onto the locked event, or refuse."""
form = EventForm(request.POST, instance=locked)
questions = QuestionFormSet(request.POST,
instance=locked)
shown.update(form=form, questions=questions)
valid = form.is_valid()
if not (questions.is_valid() and valid):
raise ValidationError('Correct the form.')
questions.save()
return ['questions'] if questions.has_changed() else []
seen = VersionForm(request.POST)
version = (seen.cleaned_data['version']
if seen.is_valid() else None)
try:
edit = event.edit(request.user, version, change)
except StaleEdit:
messages.error(request, STALE)
event = Event.objects.get(pk=event.pk)
return (EventForm(instance=event),
QuestionFormSet(instance=event))
except ValidationError:
if not shown:
raise # Busy: the lock was not taken (Chapter 33).
return shown['form'], shown['questions']
if edit.promoted:
count = len(edit.promoted)
messages.info(request, f'{count} waiting '
f'member{pluralize(count)} given places.')
return None
The page’s own part is now change(): read the form and the questions onto the locked event, or raise ValidationError to change nothing. shown keeps the bound forms so the page can show their errors. A ValidationError raised before change() ran is Chapter 33’s “busy” refusal from the lock, so it is passed on, as before.
Run the events, the registrations, and the API together:
Terminal
uv run python manage.py test events registrations api --parallel
Output
Found 489 test(s).
Creating test database for alias 'default'...
FAIL: test_cancelling_changes_the_tag_not_the_version
AssertionError: 2 != 1
Ran 489 tests in ...s
FAILED (failures=1)
Every test of the edit page, the waitlist, and the emails passes through the new path. The one failure is Chapter 47’s own, and it fails on purpose: it proved that cancelling leaves version alone, which is no longer true. Places taken still leave it alone, so the proof moves there. In api/tests/test_caching.py, the docstring becomes:
api/tests/test_caching.py
"""ETags that change whenever the answer does (Chapter 47).
The event's version counts edits, and since Chapter 48
publishing and cancelling; every place taken, and every
organizer added, leave it alone. So the tag is a hash of
the body, which changes with all of them.
"""
uv run python manage.py test events registrations api --parallel
Output
Found 489 test(s).
Creating test database for alias 'default'...
...
Ran 489 tests in ...s
OK
Step 6: The write serializer
First, the Custom Way. Save this as every.py beside manage.py, run it, then delete it:
every.py
"""The Custom Way: a ModelSerializer that takes every field."""
from rest_framework import serializers
from events.models import Event
class AllFields(serializers.ModelSerializer):
"""What a quick tutorial would write."""
class Meta:
model = Event
fields = '__all__'
event = Event.objects.order_by('pk').first()
sent = {'status': 'published', 'version': 99, 'room': 'B2'}
data = AllFields(event, data=sent, partial=True)
print('valid:', data.is_valid())
print('would save:', dict(data.validated_data))
Terminal
uv run manage.py shell -v 0 -c "exec(open('every.py').read())"
Output
valid: True
would save: {'status': 'published'}
The serializer accepts status, so saving it would publish without publish()’s checks. version is not there because the model marks it editable=False, and room was dropped without a word. Nothing was saved: the file only asked.
Now the real one. In api/serializers.py, the imports become:
api/serializers.py
from datetime import UTC
from django.core.exceptions import NON_FIELD_ERRORS
from django.core.exceptions import (
ValidationError as ModelError,
)
from django.db import models
from rest_framework import serializers
from events.models import Event
from .representation import absolute
below them:
api/serializers.py
# The fields a client may set, on a new draft or an edit.
WRITABLE = [
'title', 'description', 'starts_at', 'ends_at',
'timezone', 'location', 'capacity',
'registration_opens_at', 'registration_closes_at',
'cancellation_deadline',
]
# A rule on two fields, checked by the database, belongs to
# the field a person would change to fix it.
CONSTRAINT_FIELDS = {
'event_capacity_gt_0': 'capacity',
'event_ends_after_start': 'ends_at',
'event_opens_before_closes': 'registration_opens_at',
'event_closes_by_start': 'registration_closes_at',
'event_deadline_by_start': 'cancellation_deadline',
}
FIELD_OF_MESSAGE = {
str(rule.violation_error_message): CONSTRAINT_FIELDS[
rule.name]
for rule in Event._meta.constraints
if rule.name in CONSTRAINT_FIELDS
}
below UTCDateTimeField:
api/serializers.py
class OffsetDateTimeField(UTCDateTimeField):
"""A time from a client, which must carry its offset.
Without one, DRF would read it in the active zone: the
sender's profile zone, not the event's (N48.4).
"""
default_error_messages = {
'offset': 'Include an offset, such as Z or +05:30.',
}
def enforce_timezone(self, value):
"""Refuse a naive time; keep an aware one, in UTC."""
if value.tzinfo is None:
self.fail('offset')
return super().enforce_timezone(value)
class MyEventSerializer(serializers.ModelSerializer):
"""An organizer's own event: what they may change.
Every field here changes only through an edit, a
publish, or a cancel, and each of those is a new
version, so "v{version}" is a true ETag for it.
"""
serializer_field_mapping = UTC_MAPPING
url = serializers.SerializerMethodField()
class Meta:
model = Event
fields = ['id', 'status', *WRITABLE, 'url']
def get_url(self, event):
"""Return the full address of the event's page."""
return absolute(event.get_absolute_url())
class EventWriteSerializer(serializers.ModelSerializer):
"""What a client may send to create or change an event.
Unknown and read-only fields are refused by name, not
ignored as DRF would; times need an offset; and a new
time zone must come with the times it changes.
"""
serializer_field_mapping = {
**UTC_MAPPING,
models.DateTimeField: OffsetDateTimeField,
}
class Meta:
model = Event
fields = WRITABLE
def to_internal_value(self, data):
"""Refuse fields this serializer does not take."""
if not isinstance(data, dict):
raise serializers.ValidationError(
'Send a JSON object.')
refused = {}
for name in data:
if name in WRITABLE:
continue
refused[name] = (
'This field cannot be set through the API.'
if name in SHOWN
else 'Events have no field with this name.')
if refused:
raise serializers.ValidationError(refused)
return super().to_internal_value(data)
def validate(self, attrs):
"""Refuse a new zone without the times it moves."""
event = self.instance
zone = attrs.get('timezone')
if (event is not None and zone
and zone != event.timezone
and not {'starts_at', 'ends_at'} <= set(attrs)):
raise serializers.ValidationError({
'timezone': 'Send starts_at and ends_at with '
'a new time zone, so its times '
'are what you mean.'})
return attrs
def model_checked(event):
"""Run the model's rules on event, as the edit page does.
A rule the database checks (end after start, capacity
above 0) is reported on its field, not the request.
"""
try:
event.full_clean()
except ModelError as error:
errors = error.message_dict
for message in errors.pop(NON_FIELD_ERRORS, []):
name = FIELD_OF_MESSAGE.get(message,
NON_FIELD_ERRORS)
errors.setdefault(name, []).append(message)
raise serializers.ValidationError(errors)
OffsetDateTimeField overrides enforce_timezone(), the method DRF calls with every parsed time; a naive one fails with the field’s own message instead of being read in a zone. EventWriteSerializer.to_internal_value() runs before any field is checked, and refuses every key that is not writable, naming it. model_checked() runs full_clean() and moves the database’s two-field rules to the field a person would fix, so “An event must end after it starts” points at #/ends_at.
Step 7: The organizer’s own events
The tests, in api/tests/test_writes.py:
api/tests/test_writes.py
"""The organizer's own events: create and PATCH (Chapter 48).
A write follows the edit page's rules exactly: through
Event.save_draft() and Event.edit(), checked by the
model's full_clean(), with the version as the ETag.
"""
from datetime import timedelta
from django.test import TestCase, override_settings
from django.utils import timezone
from rest_framework.test import APIClient
from audit.models import AuditEvent
from config.helpers import in_group, save_event
from events.models import Delivery, Event
from events.tests.test_tasks import QUEUE_ONLY
from registrations.tests.test_registrations import verified
from registrations.tests.test_waitlist import full
MINE = '/api/v1/my/events/'
def iso(moment):
"""Write moment as a client would, with its offset."""
return moment.isoformat()
class Organizer(TestCase):
"""Sam, an organizer, signed in to the API."""
@classmethod
def setUpTestData(cls):
cls.sam = in_group('sam@example.org', 'Organizers')
cls.start = (timezone.now() + timedelta(days=10)
).replace(microsecond=0)
def setUp(self):
self.api = APIClient()
self.api.force_login(self.sam)
def errors(self, page):
"""Return {pointer: detail} from a 422 problem."""
self.assertEqual(page.status_code, 422, page.content)
self.assertEqual(page['Content-Type'],
'application/problem+json')
return {e['pointer']: e['detail']
for e in page.json()['errors']}
class CreateTests(Organizer):
"""POST /api/v1/my/events/."""
def draft(self, address=MINE, **changes):
fields = {'title': 'API clinic', 'location': 'Delhi',
'timezone': 'Asia/Kolkata', 'capacity': 20,
'starts_at': iso(self.start),
'ends_at': iso(self.start
+ timedelta(hours=2))}
fields.update(changes)
return self.api.post(address, fields, format='json')
def test_a_draft_its_author_organizes_recorded(self):
page = self.draft()
self.assertEqual(page.status_code, 201)
event = Event.objects.get(pk=page.json()['id'])
self.assertEqual(event.status, 'draft')
self.assertTrue(event.has_organizer(self.sam))
self.assertEqual(page['ETag'], '"v1"')
self.assertEqual(page['Location'],
f'{MINE}{event.pk}/')
self.assertTrue(AuditEvent.objects.filter(
action='create_event', target_id=event.pk).exists())
def test_status_cannot_be_set(self):
page = self.draft(status='published')
self.assertEqual(self.errors(page), {
'#/status': 'This field cannot be set through the '
'API.'})
def test_a_dry_run_saves_nothing(self):
page = self.draft(f'{MINE}?dry_run=true')
self.assertEqual(page.status_code, 200)
self.assertEqual(page.json()['event']['id'], None)
self.assertFalse(Event.objects.exists())
self.assertFalse(AuditEvent.objects.exists())
def test_a_member_who_may_not_add_events_is_refused(self):
member = verified('raj@example.org')
self.api.force_login(member)
self.assertEqual(self.draft().status_code, 403)
class PatchTests(Organizer):
"""PATCH /api/v1/my/events/{id}/ with If-Match."""
def setUp(self):
super().setUp()
self.event = save_event(starts_at=self.start,
status=Event.Status.DRAFT)
self.event.add_organizer(self.sam)
self.address = f'{MINE}{self.event.pk}/'
def patch(self, data, tag='"v1"', **query):
headers = {'If-Match': tag} if tag else {}
address = self.address + ('?dry_run=true'
if query else '')
return self.api.patch(address, data, format='json',
headers=headers)
def test_read_with_the_version_as_etag(self):
page = self.api.get(self.address)
self.assertEqual(page['ETag'], '"v1"')
self.assertEqual(page.json()['status'], 'draft')
def test_a_valid_change_is_a_new_version(self):
page = self.patch({'location': 'Room 2'})
self.assertEqual(page.status_code, 200)
self.assertEqual(page['ETag'], '"v2"')
self.event.refresh_from_db()
self.assertEqual(self.event.location, 'Room 2')
record = AuditEvent.objects.get(action='edit_event')
self.assertEqual(record.detail['fields'], ['location'])
def test_unknown_and_read_only_fields_are_named(self):
page = self.patch({'status': 'published', 'room': 'B2'})
self.assertEqual(self.errors(page), {
'#/status': 'This field cannot be set through the '
'API.',
'#/room': 'Events have no field with this name.'})
def test_a_time_without_an_offset_is_refused(self):
page = self.patch({'starts_at': '2027-03-28T17:30:00'})
self.assertEqual(self.errors(page), {
'#/starts_at': 'Include an offset, such as Z or '
'+05:30.'})
def test_a_new_zone_needs_its_times(self):
page = self.patch({'timezone': 'Asia/Kolkata'})
self.assertIn('#/timezone', self.errors(page))
def test_the_models_rules_are_field_errors(self):
page = self.patch({'capacity': 0,
'ends_at': iso(self.start)})
self.assertEqual(self.errors(page), {
'#/capacity': 'Capacity must be more than 0.',
'#/ends_at': 'An event must end after it starts.'})
def test_no_if_match_is_428(self):
page = self.patch({'location': 'Room 2'}, tag=None)
self.assertEqual(page.status_code, 428)
def test_an_old_tag_is_412_and_saves_nothing(self):
self.patch({'location': 'Room 2'})
page = self.patch({'location': 'Room 3'})
self.assertEqual(page.status_code, 412)
self.event.refresh_from_db()
self.assertEqual(self.event.location, 'Room 2')
def test_put_is_not_allowed(self):
page = self.api.put(self.address, {}, format='json')
self.assertEqual(page.status_code, 405)
def test_a_dry_run_changes_nothing(self):
page = self.patch({'location': 'Room 2'}, dry_run=True)
self.assertEqual(page.status_code, 200)
body = page.json()
self.assertEqual(body['event']['location'], 'Room 2')
self.assertEqual(body['effects']['changed'],
['location'])
self.event.refresh_from_db()
self.assertEqual((self.event.location,
self.event.version),
('Leeds Central Library', 1))
self.assertFalse(AuditEvent.objects.filter(
action='edit_event').exists())
def test_publishing_is_a_new_version(self):
self.event.description = 'Bring a laptop.'
self.event.registration_closes_at = self.start
self.event.cancellation_deadline = self.start
self.event.save()
self.event.publish()
self.assertEqual(self.api.get(self.address)['ETag'],
'"v2"')
@override_settings(TASKS=QUEUE_ONLY)
class SamePathTests(TestCase):
"""What the edit page triggers, PATCH triggers too."""
def setUp(self):
self.event = full(title='Django clinic')
self.sam = in_group('sam@example.org', 'Organizers')
self.event.add_organizer(self.sam)
self.sai = verified('sai@example.org')
self.event.join_waitlist(self.sai, timezone.now())
self.api = APIClient()
self.api.force_login(self.sam)
self.address = f'{MINE}{self.event.pk}/'
self.tag = self.api.get(self.address)['ETag']
def test_more_places_promote_the_waiting(self):
self.api.patch(self.address, {'capacity': 2},
format='json',
headers={'If-Match': self.tag})
self.assertIsNotNone(self.event.place_of(self.sai))
def test_a_new_place_tells_the_holders(self):
self.api.patch(self.address, {'location': 'Room 2'},
format='json',
headers={'If-Match': self.tag})
self.assertTrue(Delivery.objects.filter(
event=self.event, key__startswith='changed'
).exists())
def test_a_dry_run_lists_the_effects(self):
page = self.api.patch(
f'{self.address}?dry_run=true',
{'capacity': 2, 'location': 'Room 2'},
format='json', headers={'If-Match': self.tag})
effects = page.json()['effects']
self.assertEqual(effects['promoted'], 1)
self.assertGreater(effects['emails'], 0)
self.assertIsNone(self.event.place_of(self.sai))
self.assertFalse(Delivery.objects.exists())
class AccessTests(TestCase):
"""Who may use the organizer's own events."""
@classmethod
def setUpTestData(cls):
cls.sam = in_group('sam@example.org', 'Organizers')
cls.raj = in_group('raj@example.org', 'Organizers')
cls.event = save_event(status=Event.Status.DRAFT)
cls.event.add_organizer(cls.sam)
cls.address = f'{MINE}{cls.event.pk}/'
def test_a_visitor_gets_403(self):
self.assertEqual(APIClient().get(self.address)
.status_code, 403)
def test_basic_authentication_is_off(self):
page = APIClient().get(self.address, headers={
'Authorization': 'Basic c2FtQGV4YW1wbGUub3JnOng='})
self.assertEqual(page.status_code, 403)
def test_another_organizers_draft_is_404(self):
api = APIClient()
api.force_login(self.raj)
self.assertEqual(api.get(self.address).status_code, 404)
def test_a_session_write_needs_the_csrf_token(self):
api = APIClient(enforce_csrf_checks=True)
api.force_login(self.sam)
page = api.patch(self.address, {'title': 'x'},
format='json',
headers={'If-Match': '"v1"'})
self.assertEqual(page.status_code, 403)
self.assertIn('CSRF', page.json()['detail'])
SamePathTests is the reason for Step 5: a PATCH that raises the capacity promotes the member waiting, and a new location queues emails, exactly as the edit page does. AccessTests checks the defaults from Step 2: a visitor and a Basic password are refused, another organizer’s draft is a 404, and a session write without its CSRF token is refused.
Terminal
uv run python manage.py test api.tests.test_writes
Output
Found 22 test(s).
Creating test database for alias 'default'...
ERROR: test_a_dry_run_lists_the_effects
KeyError: 'etag'
ERROR: test_a_new_place_tells_the_holders
KeyError: 'etag'
ERROR: test_a_session_write_needs_the_csrf_token
ValueError: Content-Type header is "text/html;
charset=utf-8", not "application/json"
... (18 more like these)
Ran 22 tests in ...s
FAILED (failures=15, errors=6)
In api/views.py, the docstring becomes:
api/views.py
"""The API's views (Chapters 47 and 48).
The public reads, written by hand in Chapter 47, are DRF
generic views since Chapter 48, with the same answers.
The organizer's own events, at /api/v1/my/events/, are
new: create a draft, read it, and change it. Every write
goes through the model's methods, as the site's pages do.
"""
the imports:
api/views.py
import re
from django.conf import settings
from django.contrib.auth.decorators import login_not_required
from django.http import FileResponse
from django.middleware.http import ConditionalGetMiddleware
from django.shortcuts import render
from django.urls import reverse
from django.utils.cache import patch_cache_control
from django.utils.decorators import decorator_from_middleware
from django.views.decorators.http import require_safe
from rest_framework import exceptions, generics, status
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from audit.models import AuditEvent
from events.models import Event, StaleEdit
from events.views import deny, event_to_manage
from .problems import (
PreconditionFailed, PreconditionRequired, problem,
)
from .representation import absolute, listed, upcoming
from .serializers import (
EventSerializer, EventWriteSerializer, MyEventSerializer,
model_checked,
)
below conditional:
api/views.py
Action = AuditEvent.Action
and above openapi:
api/views.py
def is_dry_run(request):
"""Return whether the client asked only to try it."""
return request.query_params.get('dry_run') == 'true'
def version_in(request):
"""Return the version an If-Match names, or refuse.
No If-Match is 428; a tag that is not one of ours, such
as a weak W/ tag, can never match, so it is 412.
"""
tag = request.headers.get('If-Match')
if tag is None:
raise PreconditionRequired
found = re.fullmatch(r'"v(\d+)"', tag.strip())
if found is None:
raise PreconditionFailed
return int(found.group(1))
def with_tag(response, event):
"""Give response the organizer's ETag for event."""
response['ETag'] = f'"v{event.version}"'
return response
class MyEventCreate(generics.GenericAPIView):
"""POST /api/v1/my/events/: create a draft."""
http_method_names = ['post']
def post(self, request):
"""Save a draft by the requester, or say why not."""
if not request.user.has_perm('events.add_event'):
deny(request, Action.CREATE_EVENT)
data = EventWriteSerializer(data=request.data)
data.is_valid(raise_exception=True)
event = Event(**data.validated_data)
model_checked(event)
dry_run = is_dry_run(request)
event.save_draft(request.user, dry_run=dry_run)
body = MyEventSerializer(event).data
if dry_run:
body['id'] = None
return Response({'dry_run': True, 'event': body})
response = Response(body, status.HTTP_201_CREATED)
response['Location'] = reverse(
'api:my_event', args=[event.pk])
return with_tag(response, event)
class MyEventDetail(generics.GenericAPIView):
"""GET and PATCH /api/v1/my/events/{id}/."""
http_method_names = ['get', 'head', 'patch']
def get_object(self):
"""Return the event if the requester may change it.
As on the edit page: 404 for a draft they may not
see, 403 for an event they do not organize, both
recorded (Chapter 30).
"""
return event_to_manage(self.request,
self.kwargs['event_id'],
Action.EDIT_EVENT)
def get(self, request, event_id):
"""Send the event, with its version as the ETag."""
event = self.get_object()
response = Response(MyEventSerializer(event).data)
return with_tag(response, event)
def patch(self, request, event_id):
"""Change the fields sent, if the ETag still holds."""
event = self.get_object()
version = version_in(request)
def change(locked):
"""Check the fields sent, and set them on locked."""
data = EventWriteSerializer(
locked, data=request.data, partial=True)
data.is_valid(raise_exception=True)
for name, value in data.validated_data.items():
setattr(locked, name, value)
model_checked(locked)
return []
dry_run = is_dry_run(request)
try:
edit = event.edit(request.user, version, change,
dry_run=dry_run)
except StaleEdit:
raise PreconditionFailed from None
body = MyEventSerializer(edit.event).data
if dry_run:
return Response({'dry_run': True, 'event': body,
'effects': {
'changed': edit.changed,
'promoted': len(edit.promoted),
'emails': edit.emails}})
return with_tag(Response(body), edit.event)
Both views reuse what the site has: deny() and event_to_manage() from Chapter 30, so a refusal is the same status and the same audit record; save_draft() and edit() from Step 5. version_in() reads If-Match: missing is 428, and anything that is not one of Otahque’s strong tags is 412, since it can never match. In api/urls.py, the docstring’s chapters become (Chapters 47, 48), and above the openapi.yaml line:
uv run python manage.py test api.tests.test_writes
Output
Found 22 test(s).
Creating test database for alias 'default'...
...
Ran 22 tests in ...s
OK
Chapter 39’s guard sees two new addresses:
Terminal
uv run python manage.py test config.tests.test_public
Output
Found 3 test(s).
Creating test database for alias 'default'...
FAIL: test_a_visitor_is_sent_to_sign_in_elsewhere
AssertionError: 403 != 302 : Response didn't redirect as
expected: Response code was 403 (expected 302)
FAIL: test_a_visitor_is_sent_to_sign_in_elsewhere
AssertionError: 403 != 302 : Response didn't redirect as
expected: Response code was 403 (expected 302)
FAIL: test_exactly_these_pages_are_public
AssertionError: Items in the first set but not the second:
Ran 3 tests in ...s
FAILED (failures=3)
It treats every view without login_required as public, and DRF views have none. It needs DRF’s own rule. In config/tests/test_public.py, at the end of the docstring:
config/tests/test_public.py
Chapter 48: DRF's views opt out of the middleware and
follow DRF's own default instead, IsAuthenticated, so a
DRF view is public only if it says AllowAny, and refuses
a visitor with a 403 problem instead of a redirect.
below the django.urls import:
config/tests/test_public.py
from rest_framework.permissions import AllowAny
above LoginByDefaultTests:
config/tests/test_public.py
def drf_view(view):
"""Return the DRF view class behind view, or None."""
return getattr(view, 'cls', None)
def is_public(view):
"""Whether a visitor may open view: DRF's rule or 39's."""
api_view = drf_view(view)
if api_view is not None:
return AllowAny in api_view.permission_classes
return not getattr(view, 'login_required', True)
the first test’s set becomes:
config/tests/test_public.py
public = {name for name, _, view in own_pages()
if is_public(view)}
the second test’s loop starts:
config/tests/test_public.py
for name, route, view in own_pages():
and, above its assertRedirects:
config/tests/test_public.py
if drf_view(view) is not None:
self.assertEqual(page.status_code, 403)
self.assertEqual(page['Content-Type'],
'application/problem+json')
continue
Terminal
uv run python manage.py test config.tests.test_public
Output
Found 3 test(s).
Creating test database for alias 'default'...
...
Ran 3 tests in ...s
OK
Common Error: an organizer’s PATCH always gets 412
What you see: every PATCH answers 412, even straight after reading the event.
Why it happens: the script sends the tag without its quotes, v3 instead of "v3", or with W/ in front, which HTTP marks as a weak tag; If-Match needs a strong one, character for character.
How to fix it: send the ETag header’s value exactly as it came, quotes included.
Step 8: The contract, for writes
The tests first. In api/tests/test_openapi.py, above the test_contract import:
api/tests/test_openapi.py
from api.serializers import WRITABLE, MyEventSerializer
and in the developers page test, below the openapi.yaml check:
api/tests/test_openapi.py
# The type of an invalid-fields problem points here.
self.assertContains(page, 'id="invalid"')
Terminal
uv run python manage.py test api.tests.test_openapi
Output
Found 5 test(s).
Creating test database for alias 'default'...
ERROR: test_write_fields_match_the_api
KeyError: 'EventWrite'
FAIL: test_open_signed_out_and_linked
AssertionError: False is not true : Couldn't find
'id="invalid"' in the following response
Ran 5 tests in ...s
FAILED (failures=1, errors=1)
In docs/api/contract.md, the Errors section becomes:
docs/api/contract.md
## Errors
Every error is a problem-details body (RFC 9457), with the
type `application/problem+json`:
```json
{"type": "about:blank", "title": "Not Found",
"status": 404, "detail": "No published event has this id."}
```
| Status | When |
|---|---|
| 403 | Not signed in, or not allowed |
| 404 | No such event or address |
| 405 | A method the address does not answer; see `Allow` |
| 406 | `Accept` rules out `application/json` |
| 412 | `If-Match` names an old version |
| 422 | Invalid fields; see `errors` |
| 428 | A write without `If-Match` |
Read `status` and `type`; `detail` is for people and may
change. A 422 has the type `/developers/#invalid` and an
`errors` list, one item per problem, each with a JSON
Pointer to the field it is about:
```json
{"type": "https://otahque.tech/developers/#invalid",
"title": "Invalid fields", "status": 422,
"detail": "Some fields are invalid; see errors.",
"errors": [{"pointer": "#/capacity",
"detail": "Capacity must be more than 0."}]}
```
and the last section, which described writes as planned, becomes:
docs/api/contract.md
## The organizer's own events
The organizer's own events live at `/api/v1/my/events/`,
for members signed in who organize them: with the site's
session since Chapter 48, with a token from Chapter 50.
The list, publish, cancel, and DELETE arrive in Chapter 49.
| Method | Address | Does |
|---|---|---|
| GET | `my/events/` | My events, drafts included |
| POST | `my/events/` | Create a draft; 201 |
| GET | `my/events/{id}/` | One of my events |
| PATCH | `my/events/{id}/` | Change its details |
| POST | `my/events/{id}/publish/` | Publish a draft |
| POST | `my/events/{id}/cancel/` | Cancel a published event |
| DELETE | `my/events/{id}/` | Delete a draft |
- An organizer's event shows `id`, `status`, `url`, and
the fields it may change: `title`, `description`,
`starts_at`, `ends_at`, `timezone`, `location`,
`capacity`, `registration_opens_at`,
`registration_closes_at`, `cancellation_deadline`.
- It carries `ETag: "v{version}"`: every edit, publish,
and cancel is a new version. A PATCH must send it back
as `If-Match`: without it, 428 Precondition Required;
with an old one, 412 Precondition Failed, and nothing
is saved.
- A new `timezone` must come with `starts_at` and
`ends_at` in the same PATCH.
- Times must carry an offset (`Z` or `+05:30`); a time
without one is refused, never guessed.
- `?dry_run=true` on any write checks it and says what it
would do, and saves nothing: `{"dry_run": true,
"event": {...}, "effects": {"changed": [...],
"promoted": 1, "emails": 3}}` (a new draft has no
effects, and its `id` is null).
- Fields that may not be set (`status`, `version`,
`organizers`) are refused by name, not ignored.
- Every write goes through the same rules and records as
the site's pages.
In docs/api/openapi.yaml, the info block becomes:
docs/api/openapi.yaml
info:
title: Otahque API
version: 1.0.0
summary: Community events, for other programs.
description: >-
Read Otahque's published and cancelled events; manage
your own events if you organize them. Times are UTC;
show them in each event's timezone. The rules are in
docs/api/contract.md.
above components:, the organizer’s paths:
docs/api/openapi.yaml
/my/events/:
post:
operationId: createDraft
summary: Create a draft event that you organize.
description: >-
Checked by the same rules as the site's form. Times
must carry an offset. Add ?dry_run=true to check it
without saving.
security:
- session: []
parameters:
- $ref: '#/components/parameters/DryRun'
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/EventWrite'
responses:
'201':
description: The draft, with its ETag.
headers:
ETag:
$ref: '#/components/headers/Version'
content:
application/json:
schema:
$ref: '#/components/schemas/MyEvent'
'200':
description: A dry run; nothing was saved.
'403':
$ref: '#/components/responses/Problem'
'422':
$ref: '#/components/responses/Invalid'
/my/events/{id}/:
parameters:
- name: id
in: path
required: true
schema:
type: integer
get:
operationId: getMyEvent
summary: Read one of your events, drafts included.
security:
- session: []
responses:
'200':
description: The event; its ETag is its version.
headers:
ETag:
$ref: '#/components/headers/Version'
content:
application/json:
schema:
$ref: '#/components/schemas/MyEvent'
'403':
$ref: '#/components/responses/Problem'
'404':
$ref: '#/components/responses/Problem'
patch:
operationId: changeMyEvent
summary: Change some fields of one of your events.
description: >-
Send the ETag you read in If-Match. A new timezone
needs starts_at and ends_at too. Members holding
places are emailed about a new time or place, and a
higher capacity gives places to waiting members.
Add ?dry_run=true to see those effects first.
security:
- session: []
parameters:
- $ref: '#/components/parameters/DryRun'
- name: If-Match
in: header
required: true
schema:
type: string
example: '"v3"'
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/EventWrite'
responses:
'200':
description: The changed event, or a dry run.
headers:
ETag:
$ref: '#/components/headers/Version'
content:
application/json:
schema:
$ref: '#/components/schemas/MyEvent'
'403':
$ref: '#/components/responses/Problem'
'404':
$ref: '#/components/responses/Problem'
'412':
$ref: '#/components/responses/Problem'
'422':
$ref: '#/components/responses/Invalid'
'428':
$ref: '#/components/responses/Problem'
directly below components::
docs/api/openapi.yaml
securitySchemes:
session:
type: apiKey
in: cookie
name: sessionid
description: >-
The site's session, with its CSRF token on writes.
Tokens for programs arrive in Chapter 50.
parameters:
DryRun:
name: dry_run
in: query
required: false
description: true to check the write and save nothing.
schema:
type: boolean
directly below headers::
docs/api/openapi.yaml
Version:
description: >-
The event's version, such as "v3". Send it back in
If-Match to change the event.
schema:
type: string
EventWrite:
type: object
description: >-
The fields a client may send. Any other field is
refused by name.
properties:
title:
type: string
description:
type: string
starts_at:
type: string
format: date-time
description: With an offset, such as Z or +05:30.
ends_at:
type: string
format: date-time
timezone:
type: string
location:
type: string
capacity:
type: integer
minimum: 1
registration_opens_at:
type: [string, 'null']
format: date-time
registration_closes_at:
type: [string, 'null']
format: date-time
cancellation_deadline:
type: [string, 'null']
format: date-time
MyEvent:
allOf:
- $ref: '#/components/schemas/EventWrite'
- type: object
required: [id, status, url]
properties:
id:
type: [integer, 'null']
status:
type: string
enum: [draft, published, cancelled]
url:
type: string
format: uri
In api/templates/api/developers.html, above the contract’s card:
api/templates/api/developers.html
<section class="dev-card" aria-labelledby="dev-mine">
<h2 id="dev-mine">Your own events</h2>
<p>If you organize events, a program can create drafts
and change your events at
<code>/api/v1/my/events/</code>, under the same rules
as the site.</p>
<ul>
<li>Send the <code>ETag</code> you read back in
<code>If-Match</code>: a change someone made since
is never overwritten.</li>
<li>Add <code>?dry_run=true</code> to see what a
change would do, saving nothing.</li>
</ul>
</section>
<section class="dev-card" aria-labelledby="dev-problems">
<h2 id="dev-problems">Problems</h2>
<dl class="dev-endpoints">
<dt id="invalid">Invalid fields (422)</dt>
<dd>Each item in <code>errors</code> names a field
with a JSON Pointer, such as
<code>#/capacity</code>, and says what to fix.</dd>
<dt>Precondition (412, 428)</dt>
<dd>Read the event again, and send its new
<code>ETag</code> in <code>If-Match</code>.</dd>
</dl>
</section>
Terminal
uv run python manage.py test api.tests.test_openapi
Output
Found 5 test(s).
Creating test database for alias 'default'...
...
Ran 5 tests in ...s
OK
Step 9: The edit page’s errors, at the top
The edit page has grown long: on a phone, an error on the cancellation deadline is a long scroll below the Save button. The tests, in events/tests/test_error_summary.py:
events/tests/test_error_summary.py
"""The edit page lists its errors at the top (Chapter 48)."""
from django.test import TestCase
from django.urls import reverse
from config.helpers import as_sent, in_group, save_event
class ErrorSummaryTests(TestCase):
"""Each error, once at the top, linked to its field."""
def test_each_error_links_to_its_field(self):
event = save_event()
sam = in_group('sam@example.org', 'Organizers')
event.add_organizer(sam)
self.client.force_login(sam)
page = self.client.post(
reverse('events:edit', args=[event.pk]),
as_sent(event, capacity=0))
self.assertContains(page, 'Correct these to save')
self.assertContains(page, 'href="#id_capacity"')
def test_no_summary_without_errors(self):
event = save_event()
sam = in_group('sam@example.org', 'Organizers')
event.add_organizer(sam)
self.client.force_login(sam)
page = self.client.get(
reverse('events:edit', args=[event.pk]))
self.assertNotContains(page, 'error-summary')
Terminal
uv run python manage.py test events.tests.test_error_summary
Output
Found 2 test(s).
Creating test database for alias 'default'...
FAIL: test_each_error_links_to_its_field
AssertionError: False is not true : Couldn't find 'Correct
these to save' in the following response
Ran 2 tests in ...s
FAILED (failures=1)
A new template, templates/includes/error_summary.html:
templates/includes/error_summary.html
{# Chapter 48: every error at the top of the form, each a #}
{# link to its field, so nobody has to hunt for it (WCAG #}
{# 3.3.1). Pass form: {% include ... with form=form %}. #}
{% if form.errors %}
<div id="error-summary" class="error-summary" role="alert"
aria-labelledby="error-summary-title">
<h2 id="error-summary-title">Correct these to save</h2>
<ul>
{% for error in form.non_field_errors %}
<li>{{ error }}</li>
{% endfor %}
{% for field in form %}
{% for error in field.errors %}
<li><a href="#{{ field.id_for_label }}">
{{ field.label }}: {{ error }}</a></li>
{% endfor %}
{% endfor %}
</ul>
</div>
{% endif %}
role="alert" makes a screen reader announce the summary when the page arrives; each link jumps to its field, whose id Django set from its name. In events/templates/events/edit.html, above the <form>:
events/templates/events/edit.html
{% include "includes/error_summary.html" with form=form %}
In static/otahque/source.css, above .form-actions:
static/otahque/source.css
/* Chapter 48: the edit page's errors, listed at the top,
each a link to its field. */
.error-summary {
display: grid;
gap: 0.5rem;
padding: 1rem 1.25rem;
border: 1px solid var(--color-base-300);
border-left: 6px solid var(--color-error);
border-radius: var(--radius-box);
background-color: var(--color-base-100);
}
.error-summary h2 {
font-size: 1.125rem;
font-weight: 700;
}
.error-summary ul {
display: grid;
gap: 0.25rem;
padding-left: 1.25rem;
list-style: disc;
}
.error-summary a {
color: var(--color-error);
text-decoration: underline;
}
Terminal
npm run build
uv run python manage.py test events.tests.test_error_summary
Output
Found 2 test(s).
Creating test database for alias 'default'...
...
Ran 2 tests in ...s
OK
Step 10: In a browser
Run the server, sign in as an organizer, open one of your events’ edit pages, set the end before the start and registration to close after it, errors only the server can find, and press Save changes. Figure 48.4 shows the result.
Figure 48.4 — The edit page’s error summary.
Step 11: The checks, and the 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 670 test(s).
System check identified no issues (0 silenced).
Ran 670 tests in ...s
OK
== all checks passed
Terminal
git add .
git status --short
git commit -m "Rebuild the API with DRF; add writes"
Output
M api/problems.py
A api/serializers.py
M api/templates/api/developers.html
M api/tests/test_caching.py
M api/tests/test_openapi.py
A api/tests/test_writes.py
M api/urls.py
M api/views.py
M config/settings.py
M config/tests/test_public.py
M docs/api/contract.md
M docs/api/openapi.yaml
M events/models.py
M events/templates/events/edit.html
A events/tests/test_error_summary.py
M events/views.py
M pyproject.toml
M static/otahque/site.css
M static/otahque/source.css
A templates/includes/error_summary.html
M uv.lock
[main 1a2b3c4] Rebuild the API with DRF; add writes
21 files changed, 1317 insertions(+), 127 deletions(-)
create mode 100644 api/serializers.py
create mode 100644 api/tests/test_writes.py
create mode 100644 events/tests/test_error_summary.py
create mode 100644 templates/includes/error_summary.html
If something goes wrong
Table 48.3 — Recovery for Chapter 48
What you see
Likely cause
What to do
A DRF view answers a visitor 200
AllowAny on a view that should not have it, or REST_FRAMEWORK missing
Check the settings of Step 2; only public reads say AllowAny
Times come back in a local zone
A DateTimeField not mapped to UTCDateTimeField
Use UTC_MAPPING, as both serializers do
500 with IntegrityError on a write
The serializer saved without full_clean()
Call model_checked() before saving
A PATCH changes nothing but answers 200
The field name is misspelt, and refusal is missing
Keep EventWriteSerializer.to_internal_value()
Every PATCH is 412
The ETag sent without quotes, or a weak W/ tag
Send the ETag exactly as received
403 CSRF Failed from a script using a session
Session writes need the CSRF token
Wait for tokens (Chapter 50); scripts should not use sessions
Work through Table 48.4 from the folder that holds manage.py, with Otahque on PostgreSQL.
Table 48.4 — Verification checklist for Chapter 48
Check
Command or action
Expected result
Starting point
test --parallel
Found 645 test(s); OK
DRF, strict
uv add; check
Added; no issues
The reads with DRF
test api
25 tests OK, unchanged since Chapter 47
One edit path
test events registrations api
One failure, Chapter 47's, on purpose; then OK
The Custom Way
every.py in the shell
status accepted, room dropped
The organizer's events
test api.tests.test_writes
Red first; then 22 tests OK
Chapter 39's guard
test config.tests.test_public
Red on purpose; then 3 tests OK
The contract for writes
test api.tests.test_openapi
Red first; then 5 tests OK
The error summary
test events.tests.test_error_summary
Red first; then 2 tests OK
In a browser
The edit page with bad times, at 390 and 1280 px
Two errors at the top; the link focuses Ends
All checks
uv run python check.py
== all checks passed; Ran 670 tests
Commit
git log --oneline -1
Rebuild the API with DRF; add writes
Not verified
A real script or agent over the network; macOS and Linux shells
Chapter 50 gives programs tokens
The commands were checked in Windows PowerShell 5.1 and Git Bash, from a copy of the Chapter 47 checkpoint with a reader’s data, against PostgreSQL 18; commands that write files ran once. In Microsoft Edge, at 390 and 1280 pixels, a Playwright script opened the developers page signed out (five cards), then, signed in as Sam, sent an event’s edit page with the end before the start and registration closing after it: the summary listed both errors, and its link moved the focus to the Ends box. The browser’s own checks stopped an empty title and a capacity of 0 before they were sent, which is why the check uses errors only the server can find. One sample event was added for it and deleted afterwards.
Que. 1 Why does Otahque set DEFAULT_PERMISSION_CLASSES before writing any DRF view?
Flip to check your answerFold answer back
Answer. DRF’s views opt out of Chapter 39’s middleware, and DRF’s own default is AllowAny, so a view written without thinking would be open to everyone. With IsAuthenticated as the default, a view is public only where it says AllowAny.
Que. 2 A script sends {"status": "published"} in a PATCH. What does it get?
Flip to check your answerFold answer back
Answer. 422, with an error pointing at #/status: “This field cannot be set through the API.” Publishing goes through its own action, with its checks, in Chapter 49.
Que. 3 Why must every API time carry an offset?
Flip to check your answerFold answer back
Answer. A time without one names no instant. DRF would read it in the active zone, which is the sender’s profile zone, not the event’s, and store a wrong time without any error.
Que. 4 Why is Event.edit() on the model, not in the API’s view?
Flip to check your answerFold answer back
Answer. Because the edit page needs the same steps: the lock and version check, the audit record, promotion, and emails. In one place, a write through either door does all of them, and a change to them reaches both.
Que. 5 What does ?dry_run=true change, and what does it not?
Flip to check your answerFold answer back
Answer. It runs the same code, every check and step, inside a transaction that is then rolled back, so nothing is saved, recorded, or emailed. It does not skip any rule, so a dry run that succeeds predicts the real write, unless someone else changes the event first, which If-Match catches.
Mini-Challenge
A script misspells title as tittle. DRF’s default would answer 200 and change nothing. Write a test, in api/tests/test_rename.py, that checks Otahque names the mistake and saves nothing.
Hint:Organizer in test_writes.py signs Sam in and gives you errors().
Model answer:
api/tests/test_rename.py
"""Mini-Challenge: a misspelt field is named, not dropped."""
from datetime import timedelta
from django.utils import timezone
from rest_framework.test import APIClient
from api.tests.test_writes import MINE, Organizer
from config.helpers import save_event
class MisspeltTests(Organizer):
"""A script sends "tittle" for "title"."""
def test_the_typo_is_refused_by_name(self):
start = timezone.now() + timedelta(days=5)
event = save_event(starts_at=start)
event.add_organizer(self.sam)
api = APIClient()
api.force_login(self.sam)
page = api.patch(f'{MINE}{event.pk}/',
{'tittle': 'New name'}, format='json',
headers={'If-Match': '"v1"'})
self.assertEqual(self.errors(page), {
'#/tittle': 'Events have no field with this name.'})
event.refresh_from_db()
self.assertEqual(event.title, 'Python meetup')
Terminal
uv run python manage.py test api.tests.test_rename
Output
Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...s
OK
The model answer was run and then removed; the chapter’s checkpoint does not include it.
What We Learned
DRF’s views follow DRF’s defaults, not the project’s middleware; set them strictly before writing a view.
A serializer converts and checks, both ways, as a form does; list the fields it takes, and refuse the rest by name.
Rules live on the model; serializers and forms both run them with full_clean().
Side effects belong to one method both doors call, or they drift apart.
Times from programs carry offsets; a zone is never guessed.
If-Match with the version turns the edit page’s stale-save check into HTTP: 428 without it, 412 when old.
A dry run is the real write, rolled back.
Errors are easier to fix when they are listed where the reader starts.
Key terms
Use Table 48.5 to explain this chapter’s ideas in your own words.
Table 48.5 — Key terms from Chapter 48
Term
Meaning
Django REST framework
A package of tools for APIs on Django.
Serializer
Converts objects to data and checks incoming data.
ModelSerializer
A serializer whose fields come from a model.
validated_data
The checked, converted values after is_valid().
Overposting
Accepting fields a client should not be able to set.
Offset
The +05:30 or Z that makes a time one instant.
If-Match
Send back the ETag you read; refused if it changed.
412 Precondition Failed
The resource changed since the client read it.
428 Precondition Required
The server wants If-Match, and none was sent.
Dry run
A request that checks and reports, and saves nothing.
Error summary
A form's errors listed first, each linked to its field.
Readiness checkpoint: you are ready for Chapter 49 when uv run python check.py ends with “all checks passed” and 670 tests, api.tests.test_writes passes, your edit page lists its errors at the top, and git log --oneline -1 shows this chapter’s commit.
Git Commit
Your Chapter 48 work was committed once, in Step 11, as “Rebuild the API with DRF; add writes”: the settings, the serializers, the problems and views, the addresses, the events models and views, the contract and its OpenAPI file, the developers page, the error summary with its styles and compiled CSS, pyproject.toml and uv.lock, the two new test modules, and the three changed ones. If you kept the Mini-Challenge, commit it on its own:
Terminal
git add api/tests/test_rename.py
git commit -m "Name a misspelt field"
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 time-zone incident and to what an AI agent should be allowed to do. They are extension questions, not a gate to the next chapter. Proof files are run with uv run python manage.py shell -v 0 -c "exec(open('NAME').read())" and deleted afterwards.
L1 (Junior): What does a serializer do, and how is it like a form?
What the interviewer is testing: Can you place a serializer among things you know?
Flip to check your answerFold answer back
Perfect answer: A serializer converts in both directions. Reading, it turns an object into simple data for JSON, choosing the fields and their form; writing, it checks incoming data field by field and as a whole, and gives back the clean values or errors per field. That is a form’s job for an HTML page: a ModelForm builds fields from a model, and so does a ModelSerializer. The differences: a serializer’s input is JSON, not form fields, and its errors go back as data, not as a page. In Otahque, EventSerializer replaced Chapter 47’s dictionaries with the same output, which the unchanged contract tests prove.
Code proof: Chapter 47’s tests, against the DRF views:
Output
Found 48 test(s).
Creating test database for alias 'default'...
...
Ran 48 tests in ...s
OK
Common mistakes:
One serializer for reading and writing, so the fields a client may set are the fields it may see.
Forgetting that ModelSerializer does not run the model’s full_clean().
Follow-up the interviewer might ask:
Why does Otahque have three event serializers? (Public reads, the organizer’s view, and writes: three different lists of fields.)
L2 (Mid-Level): Predict a PATCH with “status”: “published”
What the interviewer is testing: Can you trace a write through the serializer?
Flip to check your answerFold answer back
Perfect answer: The view finds the event and checks the requester organizes it, reads the version from If-Match, and calls edit(), which locks the event and checks the version. Then change() validates with EventWriteSerializer, whose to_internal_value() runs first and refuses status by name, before any field is checked. The ValidationError leaves edit(), so its transaction is rolled back, and the handler answers 422 with an error at #/status. The draft stays a draft. With fields = '__all__', the same request would have published it, without publish()’s checks.
Figure 48.5 — A PATCH that tries to publish.
Behind the scenes:
The answer
422 application/problem+json
{"type": ".../developers/#invalid",
"errors": [{"pointer": "#/status",
"detail": "This field cannot be set through the API."}]}
Code proof: a draft, made and rolled back:
l2_proof.py
"""PATCH "status": "published" through the API."""
from datetime import timedelta
from django.db import transaction
from django.test import Client
from django.utils import timezone
from accounts.models import User
from events.models import Event
sam = User.objects.get(email='sam@example.org')
start = timezone.now() + timedelta(days=30)
with transaction.atomic():
draft = Event.objects.create(
title='Draft clinic', starts_at=start,
ends_at=start + timedelta(hours=2),
timezone='Europe/London', location='Leeds',
capacity=10)
draft.add_organizer(sam)
client = Client(HTTP_HOST='localhost')
client.force_login(sam)
answer = client.patch(
f'/api/v1/my/events/{draft.pk}/',
{'status': 'published'},
content_type='application/json',
headers={'If-Match': '"v1"'})
print(answer.status_code, answer.json()['errors'])
draft.refresh_from_db()
print('status:', draft.status)
transaction.set_rollback(True)
Output
422 [{'pointer': '#/status', 'detail': 'This field cannot be
set through the API.'}]
status: draft
Common mistakes:
Making status read-only and expecting a refusal: DRF drops read-only fields silently.
Checking for status in the view, where the next endpoint will forget to.
Follow-up the interviewer might ask:
How will an organizer publish through the API? (POST my/events/{id}/publish/, in Chapter 49, which calls publish() with its readiness checks.)
L3 (Senior): Defend one edit path for the page and the API
What the interviewer is testing: Can you see duplicated behaviour as a risk, not only duplicated code?
Flip to check your answerFold answer back
Perfect answer: Saving an event is not one write; it is a version check under a lock, the save, an audit record, promotions, and emails, in one transaction. If the API had its own copy, every future change, a new side effect, a fixed bug, would have to be made twice, and the day someone forgets, the API quietly does less than the page. Event.edit() holds the steps once, and each door supplies only what differs, how to read its input. The tests make the promise concrete: a PATCH that raises the capacity promotes, and a new place queues emails, just as on the page. The cost is that Chapter 33’s view changed shape, with its tests unchanged.
Figure 48.6 — One path for every door.
Behind the scenes:
Who calls Event.edit()
events/views.py save_edit() the edit page
api/views.py MyEventDetail PATCH
(dry run: same path, rolled back)
Code proof: the API does what the page does:
Output
Found 3 test(s).
Creating test database for alias 'default'...
...
Ran 3 tests in ...s
OK
Common mistakes:
Putting the side effects in signals, where the order and the transaction are hard to see.
Moving the form’s checks into the model method, so the method needs to know about forms.
Follow-up the interviewer might ask:
Where would a third door, an admin action, go? (Through edit() too; Chapter 33’s admin save is a candidate to move later.)
L4 (Senior): An event is stored five and a half hours off. Diagnose it
What the interviewer is testing: Can you trace a time-zone bug to the point where a zone was guessed?
Flip to check your answerFold answer back
Perfect answer: Five and a half hours is India’s offset, so a zone was applied that should not have been. The likely path: a client sent a time without an offset, and something read it in a zone. DRF’s DateTimeField reads a naive time in the active zone, and Otahque activates the requester’s profile zone: a Kolkata member’s 17:30, meant for a London event, becomes 12:00 UTC. The fix is not a better guess but no guess: Otahque’s OffsetDateTimeField refuses a naive time by name, and responses are always in UTC with the zone named. The proof shows DRF’s default reading the same text two ways.
Figure 48.7 — Diagnosing a time five and a half hours off.
Behind the scenes:
Text sent Stored (UTC)
17:30 (Kolkata user) 12:00 wrong
17:30Z 17:30 right
17:30+05:30 12:00 right, if meant
Code proof: the same text, read by DRF’s default field and by Otahque’s:
l4_proof.py
"""A naive time: DRF's default field, then Otahque's."""
from django.utils import timezone
from rest_framework import serializers
from api.serializers import OffsetDateTimeField
typed = '2026-11-19T17:30:00'
with timezone.override('Asia/Kolkata'):
plain = serializers.DateTimeField()
print('DRF default:', plain.to_internal_value(typed))
ours = OffsetDateTimeField()
try:
ours.to_internal_value(typed)
except serializers.ValidationError as error:
print('Otahque:', error.detail[0])
print('with Z:', ours.to_internal_value(typed + 'Z'))
Output
DRF default: 2026-11-19 17:30:00+05:30
Otahque: Include an offset, such as Z or +05:30.
with Z: 2026-11-19 17:30:00+00:00
Common mistakes:
“Fixing” it by reading naive times as UTC: still a guess, wrong for everyone not in UTC.
Trusting the client’s device zone, which is not the venue’s.
Follow-up the interviewer might ask:
Why does the edit page still accept local times? (A person types in the event’s zone, shown beside the box, and Chapter 24’s checks catch clock changes; a program has no such context.)
L5 (Lead): What should an AI agent with an organizer’s token be able to do?
What the interviewer is testing: Can you design permissions for a client that acts for a person and can make mistakes quickly?
Flip to check your answerFold answer back
Perfect answer: No more than the organizer could do on the site, and preferably less. The server must not trust the agent: every field, rule, and version is checked whoever sends the request, as Otahque’s write path already does. Then the agent’s own risks: it can misread, repeat, or act on stale data. So it gets a contract to read (OpenAPI), errors that name fields, If-Match against stale writes, and a dry run so a person can approve the effects before the write. Chapter 50 adds the last part: tokens limited to scopes, read, write, publish, delete, with an expiry, and every write recorded with the token that made it. I would revisit the scopes if agents start doing things organizers did not intend, which the audit trail would show.
Figure 48.8 — Limits for an AI agent.
Behind the scenes:
The agent's safe sequence
GET my/events/7/ ETag "v4"
PATCH my/events/7/?dry_run=true effects
(a person approves)
PATCH my/events/7/ If-Match "v4" 200, "v5"
Code proof: who may use the organizer’s events today:
Output
Found 4 test(s).
Creating test database for alias 'default'...
...
Ran 4 tests in ...s
OK
Common mistakes:
Giving an agent the organizer’s password, or a token that can do everything forever.
Relying on the agent’s instructions instead of the server’s checks.
Follow-up the interviewer might ask:
Should an agent be able to cancel an event? (Only with a token that has the publish scope, and after a dry run listing the emails it would send; Chapter 49 gives cancel its dry run.)
Next: Chapter 49, API views, generic views, viewsets, and routers, chooses how API views are written, and adds the list of my events, publish, cancel, and delete.