ContentsClose contents
Pre-release
Chapter 30 · Permissions, ownership, and rolesCHAPTER 30

Complete six-part pre-release for review. Adds the audit app and three migrations; no new package. Members' registrations follow in Chapter 31, check-in in 46, the API's permissions in 50, staff two-factor in 59, and the audit trail's retention and alerts in 65.

Working towards: First release (Chapter 34). One community runs free events. Members sign up, register, see, and cancel their registrations; organizers publish their own events; two people cannot both take the last place. Tests check each product rule. All milestones

CHAPTER THIRTY

Permissions, ownership, and roles

Stage 4: Accounts and first release (Chapters 24 to 34)

Prerequisites: Chapters 15 to 29, including the Chapter 29 project, its 257 passing tests, sign-in and re-authentication through django-allauth, and the organizer rules of Chapters 24 to 26

What you’ll build: A written permission matrix with a test for every row; two groups, Organizers and Administrators, created by a migration; one rule for adding and removing organizers, shared by the admin and a new Organizer access page that only administrators can open and that asks for the password again before a change; an admin that no administrator can use to promote anyone; and an audit trail that records each event action, each change of organizer access, and each refused attempt

Why This Matters

Soni wants to run a book swap in Delhi. Otahque can already hold her event, but she cannot create it: the New event page needs a permission, and today the only way to give it is for someone to open the admin, find Soni’s account, and tick permissions one by one. If they forget one, or assign her to an event without the permission, nothing works and nothing says why.

Raj organizes his own clinic, and he is curious. He opens the edit page of his event, sees /events/7/edit/ in the address bar, and types /events/8/edit/. Event 8 is Sam’s unpublished draft. Otahque has refused this since Chapter 25, but every new page must remember to refuse it too, and nothing yet proves that each one does.

One morning the community’s administrator removes Sam as an organizer of a published event, meaning to add Soni in his place, and is called away. The event now has no organizer: forty members hold places, and nobody can cancel it or answer them on Otahque’s own pages. And when someone asks who removed Sam, or who cancelled last week’s meetup, nobody can say. The admin’s log from Chapter 23 records admin saves only, and Otahque’s own pages record nothing.

These problems share one question: who may do what, to which record, and how do we know? Chapters 24 to 26 answered part of it with one method, Event.can_be_edited_by(), and promised that this chapter would finish the design. Here it is: roles that the administrator gives in one step, a rule that is checked in one place for every page, a table that lists every answer and a test that proves each one, and a record of each decision.

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

  • tell authentication from authorization, and say why Django’s staff and superuser flags are not Otahque’s roles;
  • use Django’s model permissions, a custom permission, and groups, and create groups with a migration that works on a new database;
  • explain why Django’s own has_perm() cannot answer “this event?”, and keep an object rule in one model method;
  • write a permission matrix and test every row of it, including the people who must be refused;
  • name IDOR, and decide between 404 and 403 for a refused request;
  • add and remove organizers through one rule shared by the admin and a page of your own, protected by a permission and by re-authentication;
  • record who did what, and who was refused, in an audit trail kept apart from logs.

Members’ own registrations follow in Chapter 31, check-in in Chapter 46, and the same rules behind an API in Chapter 50. Requiring two-factor sign-in for staff is Chapter 59, and keeping, trimming, and watching the audit trail is Chapter 65.

PAGE 001

What You Need to Know

Who you are, and what you may do

Authentication answers “who are you?”. Chapters 27 to 29 built it: sign-up, sign-in, sign-in codes, and two factors. Authorization answers “may you do this?”. A signed-in member is authenticated, but that alone gives no right to edit anything. Most security mistakes in web applications are authorization mistakes: the person is exactly who they claim, and the application lets them do something it should not.

Django’s user model carries two flags that look like roles and are not. Chapter 17 explained them: is_staff only lets an account open the admin site, and is_superuser grants every Django permission at once. Otahque’s roles are different: an organizer may manage the events assigned to them, and the administrator decides who organizes. Chapter 23 proved that a staff account can organize nothing, and from Chapter 26 organizers have worked without being staff. This chapter keeps the flags apart from the roles, and Table 30.1 lists the roles.

Table 30.1 — Otahque’s roles
Role What it may do
Visitor Read published and cancelled events
Member The same, and their own account pages
Organizer Create events; manage the events they are assigned to
Administrator The admin pages for accounts, assignments, events, and both logs; the Organizer access page; manages no event on Otahque's own pages
Superuser Everything, through Django; a local setup tool, not a daily account

Permissions and groups

Django gives every model four model permissions when it is migrated: add, change, delete, and view. Chapter 23 used them in the admin, and Chapters 24 and 25 used two of them on Otahque’s pages: creating an event needs events.add_event, and editing needs events.change_event. A permission is named app_label.codename, and user.has_perm('events.add_event') asks whether a user holds it.

A model can also declare its own permissions, for actions that are not add, change, delete, or view. This chapter adds one: manage_organizers, “Can manage organizer access”, on OrganizerAssignment. It names the right to open the page where organizers are added and removed, which is neither adding nor changing an assignment in the admin.

New Tool: Django groups

What problem exists? Each organizer needs the same two permissions, and each administrator the same dozen. Ticking them for each person is slow, easy to get wrong, and hard to review: nobody can see at a glance what “an organizer” may do.

What did people do before? Permissions were given to each user, and roles lived in a spreadsheet or in someone’s memory.

What is it? A Group, from django.contrib.auth, is a named set of permissions. A user in a group holds every permission the group holds, as if each had been given to them directly.

Why use it? A role is written down once, as a group, and giving the role is one step: add the member to the group. Removing them takes the role away just as quickly.

Now let’s use it. Step 4 creates Organizers and Administrators with a migration, so that every database, including the test database, has them.

Groups need care in one place. Django creates its permission rows after the last migration has run, so a new database has none while the migrations are running. A migration that looks permissions up must first ask Django to create them. Step 4 does this, and its Common Error shows what happens otherwise.

Under the Hood: permissions are remembered

The first time has_perm() runs for a user object, Django reads all of that user’s permissions from the database and keeps them on the object. Later calls on the same object do not read the database again. That is fast, and it means that adding a member to a group does not change what the same Python object answers. Even refresh_from_db() keeps the old answer. Fetch the user again, and the new answer appears. Each request fetches the user afresh, so the website is never affected: this catches tests and shell sessions. Step 5 shows it.

Rules for one object

A permission is about a model, never about one row. events.change_event says “may change events”, not “may change this event”. Otahque’s rule needs both: Sam may edit the clinic because he holds the permission and organizes it. Figure 30.1 shows the two questions, each answered in its own place.

Three numbered cards down the left joined by arrows, and one red box on the right. 1, a purple card, May this person organize?: membership of the Organizers group, set by the administrator in the admin. 2, a green card, Do they organize this event?: a current organizer assignment, added or removed on the admin or the Organizer access page. 3, a green card, Both: yes: edit, publish, cancel, delete, and copy, through Event.can_be_edited_by(). A red Not enough alone box on the right, with an arrow to card 2, says staff, superuser, or Administrators: none of them manages an event on Otahque’s pages.
Figure 30.1 — Two questions, two places.

Django’s has_perm() accepts an object, user.has_perm('events.change_event', event), but it does not answer the second question. Its standard backend, ModelBackend, returns no permissions at all when it is given an object. Django leaves rules for one object to other backends, and packages such as django-rules and django-guardian provide them.

New Concept: a rule that follows a relationship

What problem exists? “Organizers manage their own events” depends on a link between a person and a row. A list of roles cannot say which row.

What did people do before? Each view compared the event’s owner with the signed-in user, and each new view had to remember to.

What is it? A check that follows the relationship already in the data: OrganizerAssignment links a member to an event, so “does Sam organize the clinic?” is one query. OWASP’s Authorization Cheat Sheet recommends such relationship-based checks over role lists for decisions about single records.

Why use it? The rule lives where the data lives, it changes when an assignment changes, and every view can ask it the same way.

Now let’s use it. Otahque’s rule already works this way, in Event.has_organizer() and Event.can_be_edited_by(). Step 6 proves it row by row and closes one gap.

Under the Hood: the superuser shortcut

user.has_perm() answers True for any active superuser before it asks a single backend. That is how the superuser holds every permission. It also means that if Otahque moved its rule behind has_perm('events.change_event', event), every superuser could manage every event on Otahque’s pages, whatever the rule said. Chapter 25 decided that staff without an assignment use the admin instead. So Otahque keeps its rule in model methods, where the superuser is asked the same questions as everyone else. The optional lab in the interview’s L5 proves the shortcut.

Refusing without revealing: IDOR, 404, and 403

An insecure direct object reference, or IDOR, is a page that finds a record by the number in its address and forgets to check that the person may see it. Raj changes 7 to 8, and the page shows him Sam’s draft. Nothing was broken into; the page simply never asked. OWASP’s guidance is to check each object on every request, through one shared check, and to test with several accounts. Figure 30.2 follows Raj’s attempt.

Four numbered cards down the left joined by arrows, and one dashed red box on the right. 1, a blue card, Raj changes the number: /events/7/edit/ becomes /events/8/edit/, Sam’s draft. 2, a purple card, One shared check: event_to_manage() finds event 8 and asks is_visible_to(Raj). 3, a red card, 404, not 403: a draft that is not his gets not found, so the number reveals nothing. 4, a green card, Recorded: a refused AuditEvent, Raj, edit_event, event 8. A dashed red box, A page that forgets, with an arrow to card 2, says it shows Sam’s draft to anyone who types its number: that is IDOR.
Figure 30.2 — Raj changes the number.

Chapter 25 chose the answers, and OWASP’s IDOR cheat sheet gives the same advice. When the person may not even see the event, the answer is 404 Not Found, exactly what a number with no event gets, so the refusal reveals nothing. When they may see it but not change it, as with a published event that is not theirs, the answer is 403 Forbidden. A visitor who is not signed in is sent to sign in first.

A permission matrix writes every one of these answers down: a row for each kind of person, a column for each action. Figure 30.3 is Otahque’s matrix for Sam’s draft. Step 6 turns it into a test that runs every row.

A table with five columns, Person, View, Edit, Publish, and Create, and seven rows. Visitor: 404, sign in, sign in, sign in. Member: 404, 404, 404, 403. Staff only: 404, 404, 404, 403. Other organizer: 404, 404, 404, ok. Administrator: ok, 403, 403, 403. Superuser: ok, 403, 403, ok. Organizer of the draft, shaded green: ok in every column. A note below says one test row per person: PermissionMatrixTests.
Figure 30.3 — The permission matrix for Sam’s draft.

Read the administrator’s row. The administrator holds view_event, so the draft opens, but holds no assignment, so editing and publishing are refused. The superuser’s row is the same, except that the superuser may create events, because a superuser holds every permission. Neither can manage the draft on Otahque’s pages: that is the rule from Figure 30.1 at work.

Who did what: an audit trail

When something goes wrong, someone asks who did it. Otahque needs an answer for three kinds of action: changes to who may organize, actions on events, and attempts that were refused. An audit record answers it: who acted, what they did, to which record, whether it was allowed, and when. Figure 30.4 shows how it differs from the two kinds of log Otahque already has or will have.

Three boxes side by side and a banner. A green Audit record box: AuditEvent, who did what on Otahque’s pages and the admin, allowed or refused; administrators read it. A purple Admin log box: LogEntry, saves made in the admin only, since Chapter 23. A grey Diagnostic log box: errors and requests, for developers, designed in Chapter 65. A grey banner says ordinary database rows, not tamper-proof: retention, redaction, and alerts in Chapter 65.
Figure 30.4 — Three kinds of record.

New Concept: the audit record

What problem exists? The admin log covers the admin only, and diagnostic logs are written for developers, mixed with errors and requests, and thrown away after a while.

What did people do before? People searched server logs, or asked around.

What is it? A table of facts about decisions: AuditEvent, with an actor, an action, an outcome of allowed or refused, a target such as an event, a small detail, and a time. Rows are added and never changed.

Why use it? An administrator can answer “who removed Sam?” in the admin, and refused attempts, such as Raj’s, show where someone tried a door.

Now let’s use it. Step 2 builds the app, and Steps 7 to 10 write to it.

Each record is written inside the same database transaction as the action it describes. If the action fails, its record disappears with it, so the trail never claims something that did not happen. Records hold names and numbers, never private values: an edit records which fields changed, not what they held. And they are ordinary rows: anyone with access to the database could change them, so they are evidence, not proof. Chapter 65 decides how long they are kept, what is removed from them, and who is alerted.

Try it yourself

Que. 1 Sam is a superuser. Why can he not edit Raj’s clinic on Otahque’s pages, when he holds events.change_event?

Flip to check your answerFold answer back

Answer. Editing needs two things: the permission and a current assignment for that event. Sam holds the permission but does not organize Raj’s clinic, so can_be_edited_by() answers False and the page answers 403. He can still correct the event in the admin, where his changes are logged.

Que. 2 Raj types the number of an event that does not exist, then the number of Sam’s draft. What does he see, and which attempt is recorded?

Flip to check your answerFold answer back

Answer. He sees “not found” both times, so he cannot tell which number belongs to a real event. Only the second is recorded, as a refused attempt on Sam’s draft: an unknown number has no event to record against.

PAGE 002

How We Build It

Start from Chapter 29, in the folder containing manage.py, with your own .env, the locked environment, 257 passing tests, every migration applied, and Sam’s superuser password from Chapter 18. No package is added. The new files are the audit app, three migrations, two templates, a template filter, docs/design/permissions.md, and docs/adr/ADR-004-access-rules.md. The commands are written the same for Windows PowerShell, Git Bash, macOS, Linux, and WSL; the chapter’s checks ran in the first two. Each step with new behaviour writes its tests first and runs them to see them fail. Steps 5 and 6 prove behaviour that already exists, so most of their checks pass at once.

The tests share one new helper from Step 5: in_group() makes a member with a password and puts them in a group. Earlier helpers keep their jobs: member() makes a member holding named permissions, future_draft() a complete draft that starts next week, and action_url() the address of an event action.

The Custom Way

Many tutorials check ownership inside each view, with an if that compares the event with the signed-in user. Save this practice file as s_idor.py beside manage.py, run it with uv run python manage.py shell -c "exec(open('s_idor.py').read())", and delete it. It makes demo members and a draft inside a transaction it rolls back, so your rows are unchanged:

from datetime import timedelta

from django.db import transaction
from django.http import Http404, HttpResponse
from django.test import RequestFactory
from django.utils import timezone

from accounts.models import User
from events.models import Event


def edit_by_hand(request, event_id):
    """Check access inside the view, by hand."""
    event = Event.objects.get(pk=event_id)
    if not event.organizer_assignments.filter(
            member=request.user,
            revoked_at__isnull=True).exists():
        raise Http404
    return HttpResponse(f'Edit form for {event.title}')


def copy_by_hand(request, event_id):
    """Show the copy form; its author forgot the check."""
    event = Event.objects.get(pk=event_id)
    return HttpResponse(f'Copy form for {event.title}')


with transaction.atomic():
    sam = User.objects.create_user(
        'sam.demo@example.org', display_name='Sam demo')
    raj = User.objects.create_user(
        'raj.demo@example.org', display_name='Raj demo')
    start = timezone.now() + timedelta(days=7)
    draft = Event.objects.create(
        title='Sam demo draft', starts_at=start,
        ends_at=start + timedelta(hours=2),
        timezone='UTC', location='Leeds', capacity=20)
    draft.add_organizer(sam)
    request = RequestFactory().get('/')
    request.user = raj
    try:
        edit_by_hand(request, draft.pk)
    except Http404:
        print('edit, checked by hand: 404')
    page = copy_by_hand(request, draft.pk)
    print('copy, check forgotten:', page.status_code,
          page.content.decode())
    transaction.set_rollback(True)
edit, checked by hand: 404
copy, check forgotten: 200 Copy form for Sam demo draft

The first view checks, and Raj gets 404. The second, written later by someone in a hurry, does not, and Raj sees Sam’s draft: an IDOR. Nothing in the code looks wrong; the check is simply missing, and no test asked. The Django Way keeps the rule in one model method that every view calls through one shared helper, event_to_manage(), and writes a test for every row of the matrix, so a new page that forgets is caught by the tests, not by Raj.

The Django Way

Step 1: Check the starting point

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

OK
Destroying test database for alias 'default'...
git status --short
git log --oneline -1
... Add password reset, codes, and two factors

Step 2: An app for the audit trail

The audit trail will hold records about events, accounts, and later registrations, so it gets its own app rather than living inside one of them, for the same reason Chapter 20 gave registrations their own. Create it:

uv run python manage.py startapp audit

Give the generated audit/apps.py its two docstrings, as Chapter 7 did for events/apps.py:

"""Configuration Django reads to load the audit app."""
from django.apps import AppConfig


class AuditConfig(AppConfig):
    """The audit app: who did what, and whether allowed."""

    name = 'audit'

In config/settings.py, add it to INSTALLED_APPS, after the registrations line:

    'audit.apps.AuditConfig',

Tests first. Replace the generated audit/tests.py with:

"""Tests for the audit app."""
from django.contrib.auth.models import AnonymousUser
from django.db import IntegrityError, transaction
from django.test import TestCase
from django.urls import reverse

from accounts.models import User

from .models import AuditEvent, record

Action = AuditEvent.Action


class AuditEventTests(TestCase):
    """Audit rows: what they hold, and that they stay."""

    @classmethod
    def setUpTestData(cls):
        cls.sam = User.objects.create_superuser(
            'sam@example.org', display_name='Sam'
        )

    def test_a_row_names_actor_action_and_target(self):
        row = record(self.sam, Action.JOIN_ORGANIZERS,
                     self.sam, note='by hand')
        self.assertEqual(
            (row.actor, row.action, row.outcome,
             row.target_type, row.target_id, row.detail),
            (self.sam, 'join_organizers', 'allowed',
             'user', self.sam.pk, {'note': 'by hand'}),
        )

    def test_visitors_and_scripts_have_no_actor(self):
        for actor in (AnonymousUser(), None):
            with self.subTest(actor=actor):
                row = record(actor, Action.VIEW_EVENT)
                self.assertIsNone(row.actor)
                self.assertEqual(row.target_type, '')

    def test_outcome_is_allowed_or_refused(self):
        with self.assertRaises(IntegrityError):
            with transaction.atomic():
                AuditEvent.objects.create(
                    action=Action.VIEW_EVENT,
                    outcome='maybe',
                )

    def test_the_admin_page_is_view_only(self):
        row = record(self.sam, Action.VIEW_EVENT)
        self.client.force_login(self.sam)
        name = 'admin:audit_auditevent'
        listing = self.client.get(
            reverse(f'{name}_changelist')
        )
        self.assertContains(listing, 'View an event')
        add = self.client.get(reverse(f'{name}_add'))
        self.assertEqual(add.status_code, 403)
        change = reverse(f'{name}_change', args=[row.pk])
        self.assertNotContains(self.client.get(change),
                               'name="_save"')
        delete = reverse(f'{name}_delete', args=[row.pk])
        response = self.client.post(delete, {'post': 'yes'})
        self.assertEqual(response.status_code, 403)
        self.assertEqual(AuditEvent.objects.count(), 1)

The four tests say what a record holds, that a visitor or a script has no actor, that the outcome is only “allowed” or “refused”, and that the admin page cannot add, change, or delete a record, even for a superuser.

uv run python manage.py test audit
Found 1 test(s).
Creating test database for alias 'default'...
...
ImportError: Failed to import test module: audit.tests
Ran 1 test in ...s

FAILED (errors=1)
Destroying test database for alias 'default'...

Now the model. Replace audit/models.py with:

"""The audit trail: who did what, and whether allowed."""
from django.conf import settings
from django.db import models
from django.utils import timezone


class AuditEvent(models.Model):
    """Who did what to which record, and whether allowed.

    Rows are added, never changed.
    """

    class Action(models.TextChoices):
        """What the person tried to do."""

        CREATE_EVENT = 'create_event', 'Create an event'
        VIEW_EVENT = 'view_event', 'View an event'
        EDIT_EVENT = 'edit_event', 'Edit an event'
        PUBLISH_EVENT = 'publish_event', 'Publish an event'
        CANCEL_EVENT = 'cancel_event', 'Cancel an event'
        DELETE_EVENT = 'delete_event', 'Delete a draft'
        COPY_EVENT = 'copy_event', 'Copy an event'
        MANAGE_ORGANIZERS = (
            'manage_organizers', 'Open organizer access'
        )
        ADD_ORGANIZER = 'add_organizer', 'Add an organizer'
        REMOVE_ORGANIZER = (
            'remove_organizer', 'Remove an organizer'
        )
        JOIN_ORGANIZERS = (
            'join_organizers', 'Join the Organizers group'
        )
        LEAVE_ORGANIZERS = (
            'leave_organizers', 'Leave the Organizers group'
        )

    class Outcome(models.TextChoices):
        """Whether Otahque allowed it."""

        ALLOWED = 'allowed', 'Allowed'
        REFUSED = 'refused', 'Refused'

    actor = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.PROTECT,
        null=True, blank=True,
        related_name='audit_events',
    )
    action = models.CharField(max_length=40, choices=Action)
    outcome = models.CharField(
        max_length=10, choices=Outcome,
        default=Outcome.ALLOWED,
    )
    target_type = models.CharField(max_length=40, blank=True)
    target_id = models.BigIntegerField(null=True, blank=True)
    detail = models.JSONField(default=dict, blank=True)
    created_at = models.DateTimeField(default=timezone.now)

    class Meta:
        ordering = ['-created_at', '-id']
        default_permissions = ['view']
        constraints = [
            models.CheckConstraint(
                condition=models.Q(outcome__in=[
                    'allowed', 'refused',
                ]),
                name='audit_outcome_valid',
                violation_error_message=(
                    'Outcome must be allowed or refused.'
                ),
            ),
        ]

    def __str__(self):
        return f'{self.get_action_display()}: {self.outcome}'


def record(actor, action, target=None,
           outcome=AuditEvent.Outcome.ALLOWED, **detail):
    """Add one audit row.

    Call it inside the action's own transaction, so a failed
    action leaves no row.
    """
    if actor is not None and not actor.is_authenticated:
        actor = None
    return AuditEvent.objects.create(
        actor=actor,
        action=action,
        outcome=outcome,
        target_type=(target._meta.model_name
                     if target is not None else ''),
        target_id=target.pk if target is not None else None,
        detail=detail,
    )

Action lists every action the trail knows, with words an administrator can read. The target is two plain fields, a type such as event and a number, not a foreign key: when a draft is deleted, its records stay, pointing at a number that no longer exists. Chapter 55 shows the generic relation that could replace them, and its costs. default_permissions = ['view'] gives the model only a view permission, so there is no add, change, or delete permission to grant by mistake. record() is the one way the rest of Otahque writes a row; it turns a signed-out visitor into no actor.

Replace audit/admin.py with a page that can only be read:

"""Admin pages for the audit trail."""
from django.contrib import admin

from .models import AuditEvent


@admin.register(AuditEvent)
class AuditEventAdmin(admin.ModelAdmin):
    """The audit trail, read-only."""

    list_display = ['created_at', 'actor', 'action',
                    'outcome', 'target_type', 'target_id']
    list_filter = ['outcome', 'action']
    list_select_related = ['actor']
    search_fields = ['actor__email']

    def has_add_permission(self, request):
        """Only Otahque's own code adds audit rows."""
        return False

    def has_change_permission(self, request, obj=None):
        """Audit rows are never edited."""
        return False

    def has_delete_permission(self, request, obj=None):
        """Audit rows are never deleted."""
        return False

The three has_*_permission methods return False even for a superuser, because a superuser holds every permission, including ones a model does not define. Make the migration and apply it:

uv run python manage.py makemigrations audit
Migrations for 'audit':
  audit/migrations/0001_initial.py
    + Create model AuditEvent
uv run python manage.py migrate
Operations to perform:
  Apply all migrations: account, accounts, admin, audit,
    auth, contenttypes, events, mfa, registrations, sessions,
    socialaccount
Running migrations:
  Applying audit.0001_initial... OK
uv run python manage.py test audit
Found 4 test(s).
Creating test database for alias 'default'...
...
Ran 4 tests in ...s

OK
Destroying test database for alias 'default'...

Step 3: A permission for organizer access

In events/models.py, add a custom permission to OrganizerAssignment’s Meta, after its ordering line:

        permissions = [
            ('manage_organizers',
             'Can manage organizer access'),
        ]

Each entry is a code name and a label. Django adds the permission row when the migration runs, as events.manage_organizers. A change to Meta.permissions needs a migration, like any other model change:

PowerShell. The command is long, so it is split. The backtick continues the command onto the next line; put no spaces after it:

uv run python manage.py makemigrations events `
  --name manage_organizers

Git Bash, macOS, Linux, or WSL. The backslash continues the command; put no spaces after it:

uv run python manage.py makemigrations events \
  --name manage_organizers
Migrations for 'events':
  events/migrations/0005_manage_organizers.py
    ~ Change Meta options on organizerassignment
uv run python manage.py migrate
Operations to perform:
  Apply all migrations: account, accounts, admin, audit,
    auth, contenttypes, events, mfa, registrations, sessions,
    socialaccount
Running migrations:
  Applying events.0005_manage_organizers... OK

Step 9 checks this permission before the Organizer access page opens.

Step 4: Two groups, made by a migration

Name the Organizers group once, in events/models.py, after the CAPACITY_MESSAGE line:

ORGANIZERS = 'Organizers'

Tests first. In accounts/tests.py, change the AnonymousUser import to:

from django.contrib.auth.models import AnonymousUser, Group

and add at the end of the file:

# Chapter 30: the two groups the migration creates.
GROUPS = {
    'Administrators': [
        'accounts.change_user', 'accounts.view_user',
        'admin.view_logentry', 'audit.view_auditevent',
        'events.change_event',
        'events.add_organizerassignment',
        'events.change_organizerassignment',
        'events.view_organizerassignment',
        'events.delete_event', 'events.manage_organizers',
        'events.view_event',
        'registrations.view_registration',
    ],
    'Organizers': [
        'events.add_event', 'events.change_event',
    ],
}


class GroupTests(TestCase):
    """The two groups and the permissions they hold."""

    def test_two_groups_with_exactly_these_permissions(self):
        found = {
            group.name: sorted(
                f'{p.content_type.app_label}.{p.codename}'
                for p in group.permissions.all()
            )
            for group in Group.objects.all()
        }
        expected = {name: sorted(perms)
                    for name, perms in GROUPS.items()}
        self.assertEqual(found, expected)

The test lists each group’s permissions exactly: none missing, and none extra. An extra permission would quietly widen a role, so the test fails on that too.

uv run python manage.py test accounts.tests.GroupTests
Found 1 test(s).
Creating test database for alias 'default'...
...
AssertionError: {} != {'Administrators':
    ['accounts.change_user'[362 chars]nt']}
Ran 1 test in ...s

FAILED (failures=1)
Destroying test database for alias 'default'...

A data migration changes rows rather than tables; Chapter 18 wrote one. Make an empty one in accounts:

PowerShell. As in Step 3, the command is split. The backtick continues the command onto the next line; put no spaces after it:

uv run python manage.py makemigrations accounts `
  --empty --name groups

Git Bash, macOS, Linux, or WSL. The backslash continues the command; put no spaces after it:

uv run python manage.py makemigrations accounts \
  --empty --name groups
Migrations for 'accounts':
  accounts/migrations/0004_groups.py

Keep the file’s first line, the comment with your date, and replace everything below it with:

from django.contrib.auth.management import create_permissions
from django.db import migrations

GROUPS = {
    'Organizers': [
        'events.add_event', 'events.change_event',
    ],
    'Administrators': [
        'accounts.view_user', 'accounts.change_user',
        'admin.view_logentry', 'audit.view_auditevent',
        'events.view_event', 'events.change_event',
        'events.delete_event',
        'events.view_organizerassignment',
        'events.add_organizerassignment',
        'events.change_organizerassignment',
        'events.manage_organizers',
        'registrations.view_registration',
    ],
}


def create_groups(apps, schema_editor):
    """Create both groups with their permissions."""
    # Django adds permissions after the last migration, so
    # a new database has none yet: create them first.
    for config in apps.get_app_configs():
        config.models_module = True
        create_permissions(config, apps=apps, verbosity=0)
        config.models_module = None
    Group = apps.get_model('auth', 'Group')
    Permission = apps.get_model('auth', 'Permission')
    for name, perms in GROUPS.items():
        group, _ = Group.objects.get_or_create(name=name)
        group.permissions.set([
            Permission.objects.get(
                content_type__app_label=perm.split('.')[0],
                codename=perm.split('.')[1],
            )
            for perm in perms
        ])


def remove_groups(apps, schema_editor):
    """Delete both groups again."""
    Group = apps.get_model('auth', 'Group')
    Group.objects.filter(name__in=GROUPS).delete()


class Migration(migrations.Migration):

    dependencies = [
        ('accounts', '0003_profile'),
        ('admin', '0003_logentry_add_action_flag_choices'),
        ('audit', '0001_initial'),
        ('events', '0005_manage_organizers'),
        ('registrations', '0002_rules'),
    ]

    operations = [
        migrations.RunPython(create_groups, remove_groups),
    ]

GROUPS is the whole design of the two roles in twenty lines. Organizers hold the two permissions Chapters 24 and 25 asked for. Administrators hold what the admin pages need and the new manage_organizers, but not add_event: an administrator who also organizes joins Organizers too. create_groups() first asks Django to create the permission rows, for the reason the Common Error below explains, then creates each group or finds it, and sets its permissions to exactly the list. remove_groups() makes the migration reversible. The dependencies list each migration whose permissions it needs, so Django runs them first.

uv run python manage.py migrate
Operations to perform:
  Apply all migrations: account, accounts, admin, audit,
    auth, contenttypes, events, mfa, registrations, sessions,
    socialaccount
Running migrations:
  Applying accounts.0004_groups... OK
uv run python manage.py test accounts.tests.GroupTests
Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...s

OK
Destroying test database for alias 'default'...

Common Error: “Permission matching query does not exist”

Leave out the create_permissions() loop, and migrate still succeeds on your own database, because your earlier migrations already left the permission rows behind. The tests then fail with Permission matching query does not exist, and so would every new database, including the one Chapter 63 deploys: Django creates permissions only after the last migration, and a new database has none yet. Keep the loop. The models_module lines are needed because the app configurations a migration sees are historical copies with no models module, and Django skips those.

Make an administrator. In a private window, sign up at http://127.0.0.1:8000/accounts/signup/ as admin@example.org, with the display name “Community admin” and a password of 15 characters or more, and close the window. Then, signed in to the admin as Sam, open Users, choose admin@example.org, tick Staff status, select Administrators in the Groups list, and save. For now the list is a plain one, so to keep a group that is already selected, hold Ctrl (Cmd on a Mac) while you click; Step 8 finds out why and brings back Django’s two-box picker. This is the superuser’s one remaining job: setting up the accounts that do the daily work. Sign up soni@example.org, display name “Soni”, the same way; Step 8 gives her the Organizers group.

Step 5: The permission cache

Before writing tests that add members to groups, watch the behaviour that catches such tests. In events/tests.py, change the Permission import and the .models import to:

from django.contrib.auth.models import Group, Permission
from .models import ORGANIZERS, Event, OrganizerAssignment

and add at the end:

def in_group(email, group, **flags):
    """Add a member with SAI_PASSWORD to the named group."""
    name = email.split('@')[0].title()
    user = User.objects.create_user(
        email, SAI_PASSWORD, display_name=name, **flags
    )
    user.groups.add(Group.objects.get(name=group))
    return user


class PermissionCacheTests(TestCase):
    """A user's permissions are cached until refetched."""

    def test_a_new_group_needs_a_fresh_user(self):
        soni = member('soni@example.org')
        self.assertFalse(soni.has_perm('events.add_event'))
        soni.groups.add(Group.objects.get(name=ORGANIZERS))
        self.assertFalse(soni.has_perm('events.add_event'))
        soni.refresh_from_db()
        self.assertFalse(soni.has_perm('events.add_event'))
        soni = User.objects.get(pk=soni.pk)
        self.assertTrue(soni.has_perm('events.add_event'))
uv run python manage.py test events.tests.PermissionCacheTests
Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...s

OK
Destroying test database for alias 'default'...

The test passes at once: it records Django’s behaviour rather than changing it. After groups.add(), the same object still says no, and so does refresh_from_db(); only a freshly fetched user says yes.

Common Error: a group added, and still 403

A test adds Soni to Organizers, then calls soni.has_perm() on the same object and gets False, or signs her in with force_login(soni) after asking has_perm() once, and is puzzled by a refusal that should not happen. Fetch the user again with User.objects.get(pk=soni.pk) before asking. A request through the test client always fetches the user afresh, so self.client.get() sees the new group.

Step 6: The matrix, row by row

Turn Figure 30.3 into a test. Add at the end of events/tests.py:

class ActiveOrganizerTests(TestCase):
    """Only active, current organizers count."""

    def test_an_inactive_organizer_sees_no_draft(self):
        sam = in_group('sam@example.org', ORGANIZERS)
        draft = future_draft(sam)
        self.assertTrue(draft.is_visible_to(sam))
        sam.is_active = False
        sam.save()
        self.assertFalse(draft.has_organizer(sam))
        self.assertFalse(draft.is_visible_to(sam))


# What each person gets on Sam's draft (Chapter 30).
MATRIX = [
    # person, view, edit, publish, create
    ('visitor', '404', 'sign in', 'sign in', 'sign in'),
    ('member', '404', '404', '404', '403'),
    ('staff only', '404', '404', '404', '403'),
    ('other organizer', '404', '404', '404', 'ok'),
    ('administrator', 'ok', '403', '403', '403'),
    ('superuser', 'ok', '403', '403', 'ok'),
    # Last: this row publishes the draft.
    ('organizer', 'ok', 'ok', 'ok', 'ok'),
]


def outcome(response):
    """Name a response as the matrix names it."""
    code = response.status_code
    if code == 302 and response.url.startswith(
            reverse('account_login')):
        return 'sign in'
    return {200: 'ok', 302: 'ok'}.get(code, str(code))


class PermissionMatrixTests(TestCase):
    """Each person against each page: the full matrix."""

    @classmethod
    def setUpTestData(cls):
        sam = in_group('sam@example.org', ORGANIZERS)
        raj = in_group('raj@example.org', ORGANIZERS)
        cls.draft = future_draft(sam)
        future_draft(raj, title='Delhi clinic')
        cls.people = {
            'visitor': None,
            'member': member('sai@example.org'),
            'staff only': User.objects.create_user(
                'staff@example.org', display_name='Staff',
                is_staff=True,
            ),
            'other organizer': raj,
            'administrator': in_group(
                'admin@example.org', 'Administrators',
                is_staff=True,
            ),
            'superuser': User.objects.create_superuser(
                'root@example.org', display_name='Root'
            ),
            'organizer': sam,
        }

    def answers(self):
        """List this person's outcomes, page by page."""
        draft = self.draft
        return [
            outcome(self.client.get(
                draft.get_absolute_url())),
            outcome(self.client.get(edit_url(draft))),
            outcome(self.client.post(
                action_url('publish', draft))),
            outcome(self.client.get(
                reverse('events:create'))),
        ]

    def test_every_row(self):
        for person, *expected in MATRIX:
            self.client.logout()
            if self.people[person]:
                self.client.force_login(self.people[person])
            with self.subTest(person=person):
                self.assertEqual(self.answers(), expected)

MATRIX is the figure as data: one row per person, one column per action. outcome() names a response the way the matrix does, and test_every_row() signs each person in, makes the four requests, and compares the answers with the row, inside subTest(), so a failure names the person. The organizer’s row comes last because publishing changes the draft. ActiveOrganizerTests asks one more question: what happens when an organizer’s account is made inactive?

uv run python manage.py test events -k Matrix -k Active
Found 2 test(s).
Creating test database for alias 'default'...
...
AssertionError: True is not false
Ran 2 tests in ...s

FAILED (failures=1)
Destroying test database for alias 'default'...

Every matrix row already passes: Chapters 24 to 26 built these rules, and now each one is proved. The inactive organizer fails: has_organizer() never looked at is_active, so is_visible_to() still shows such an organizer the draft. Signing in already refuses inactive accounts, so this is not an open door today, but a rule should not depend on another layer to hold. In events/models.py, replace has_organizer() with:

    def has_organizer(self, user):
        """Return True for an active, current organizer."""
        if not (user.is_authenticated and user.is_active):
            return False
        return self.organizer_assignments.filter(
            member=user, revoked_at__isnull=True
        ).exists()
uv run python manage.py test events -k Matrix -k Active
Found 2 test(s).
Creating test database for alias 'default'...
...
Ran 2 tests in ...s

OK
Destroying test database for alias 'default'...

-k runs every test whose name contains the text after it, and two -k options run the tests matching either.

Step 7: One rule for adding and removing organizers

Organizers will be added and removed in two places, the admin and a page of Otahque’s own. Both must refuse the same cases, so the rule goes in the models, where both can call it. Tests first. Add the audit import after the .models import of events/tests.py:

from audit.models import AuditEvent

and at the end of the file:

class OrganizerRuleTests(TestCase):
    """Granting and revoking organizers, with records."""

    @classmethod
    def setUpTestData(cls):
        cls.admin = in_group(
            'admin@example.org', 'Administrators',
            is_staff=True,
        )
        cls.sam = in_group('sam@example.org', ORGANIZERS)
        cls.soni = in_group('soni@example.org', ORGANIZERS)
        cls.event = future_draft(cls.sam)

    def test_an_organizer_is_added_and_recorded(self):
        self.event.grant_organizer(self.soni, self.admin)
        self.assertTrue(self.event.has_organizer(self.soni))
        row = AuditEvent.objects.get()
        self.assertEqual(
            (row.actor, row.action, row.outcome,
             row.target_id, row.detail),
            (self.admin, 'add_organizer', 'allowed',
             self.event.pk, {'member': self.soni.pk}),
        )

    def test_only_the_organizers_group_may_organize(self):
        sai = member('sai@example.org')
        with self.assertRaisesMessage(
                ValidationError,
                'Only members of the Organizers group'):
            self.event.grant_organizer(sai, self.admin)
        self.assertFalse(self.event.has_organizer(sai))
        self.assertEqual(AuditEvent.objects.get().outcome,
                         'refused')

    def test_an_inactive_member_is_refused(self):
        self.soni.is_active = False
        self.soni.save()
        with self.assertRaisesMessage(
                ValidationError, 'account is not active'):
            self.event.grant_organizer(self.soni, self.admin)

    def test_the_last_organizer_stays(self):
        for status in ('draft', 'published'):
            event = future_draft(self.sam, status=status)
            place = event.organizer_assignments.get()
            with self.subTest(status=status):
                with self.assertRaisesMessage(
                        ValidationError,
                        'Assign another organizer'):
                    place.revoke(self.admin)
                place.refresh_from_db()
                self.assertIsNone(place.revoked_at)

    def test_a_cancelled_event_may_lose_them_all(self):
        event = future_draft(self.sam, status='cancelled')
        place = event.organizer_assignments.get()
        place.revoke(self.admin)
        self.assertIsNotNone(place.revoked_at)

    def test_one_of_two_may_go_and_is_refused_next(self):
        self.event.grant_organizer(self.soni, self.admin)
        self.client.force_login(self.sam)
        url = edit_url(self.event)
        self.assertEqual(
            self.client.get(url).status_code, 200
        )
        place = self.event.organizer_assignments.get(
            member=self.sam
        )
        place.revoke(self.admin)
        self.assertEqual(
            self.client.get(url).status_code, 404
        )
uv run python manage.py test events.tests.OrganizerRuleTests
Found 6 test(s).
Creating test database for alias 'default'...
...
AttributeError: 'OrganizerAssignment' object has no attribute
    'revoke'
Ran 6 tests in ...s

FAILED (errors=7)
Destroying test database for alias 'default'...

In events/models.py, add the import after from django.utils import timezone, with a blank line before it:

from audit.models import AuditEvent, record

then, after the ORGANIZERS line:

ADDED = AuditEvent.Action.ADD_ORGANIZER
REMOVED = AuditEvent.Action.REMOVE_ORGANIZER
REFUSED = AuditEvent.Outcome.REFUSED


def organizer_problem(member):
    """Why member cannot organize events, or None."""
    if not member.is_active:
        return 'This member’s account is not active.'
    if not member.groups.filter(name=ORGANIZERS).exists():
        return ('Only members of the Organizers group can '
                'organize events.')
    return None

and this method on Event, before is_visible_to():

    def grant_organizer(self, member, by):
        """Make member an organizer at by's request.

        Otherwise raise ValidationError. Both are recorded.
        """
        problem = organizer_problem(member)
        if problem:
            record(by, ADDED, self, REFUSED,
                   member=member.pk)
            raise ValidationError(problem)
        if self.has_organizer(member):
            raise ValidationError(
                'This member already organizes this event.'
            )
        with transaction.atomic():
            assignment = self.add_organizer(member)
            record(by, ADDED, self, member=member.pk)
        return assignment

organizer_problem() says why someone cannot organize, in words an administrator can act on, or None. grant_organizer() records a refusal before raising it, and adds the assignment and its record in one transaction. A duplicate is refused without a record: it is a slip, not an attempt at access. add_organizer() from Chapter 24 stays as it is: creating or copying an event makes its creator an organizer without these checks, because the creator already passed the page’s own.

Add this method to OrganizerAssignment, after __str__():

    def revoke(self, by):
        """End this assignment now at by's request.

        Otherwise raise ValidationError. Both are recorded.
        """
        event = self.event
        others = event.organizer_assignments.filter(
            revoked_at__isnull=True
        ).exclude(pk=self.pk)
        if (event.status != Event.Status.CANCELLED
                and not others.exists()):
            record(by, REMOVED, event, REFUSED,
                   member=self.member_id)
            raise ValidationError(
                'Assign another organizer before removing '
                'the last one.'
            )
        with transaction.atomic():
            self.revoked_at = timezone.now()
            self.save(update_fields=['revoked_at'])
            record(by, REMOVED, event, member=self.member_id)

revoke() keeps the row and sets revoked_at, as Chapter 20 designed, and refuses to remove the last current organizer of a draft or published event: that event would have nobody able to cancel it or answer its members. A cancelled event may lose them all. Replacing an organizer still works: add the new one first.

uv run python manage.py test events.tests.OrganizerRuleTests
Found 6 test(s).
Creating test database for alias 'default'...
...
Ran 6 tests in ...s

OK
Destroying test database for alias 'default'...

Two administrators removing the two organizers of one event at the same moment could each see the other still there. Chapter 33 teaches the locking that closes such races; locally, with one person at a time, the rule holds.

Step 8: The admin, made safe

Until now, the admin added any member as an organizer, removed one by typing a date, and let anyone who may change users change their permissions. With an Administrators group, that last point matters: an administrator could tick every permission for themselves, or add anyone to Administrators. This is called privilege escalation, and the fix is that an administrator who is not a superuser may change only Organizers membership.

Tests first. In events/tests.py, replace Chapter 23’s revoke_form() helper with:

def remove_selected(client, *assignments):
    """Run the admin's Remove selected organizers action."""
    return client.post(
        admin_url(OrganizerAssignment, 'changelist'),
        {'action': 'remove_selected',
         '_selected_action': [a.pk for a in assignments]},
        follow=True,
    )

In OrganizerAssignmentAdminTests, keep setUpTestData() up to Sai’s account, and replace the rest of the class, up to test_list_runs_a_fixed_number_of_queries(), with:

        # Chapter 30: only the Organizers group organizes.
        organizers = Group.objects.get(name=ORGANIZERS)
        cls.sai.groups.add(organizers)

    def setUp(self):
        self.client.force_login(self.sam)

    def add(self, member=None):
        """Assign member, Sai by default, in the admin."""
        member = member or self.sai
        return self.client.post(
            admin_url(OrganizerAssignment, 'add'),
            {'event': self.event.pk, 'member': member.pk},
        )

    def test_add_and_remove_but_never_delete(self):
        self.event.add_organizer(self.sam)
        self.add()
        assignment = OrganizerAssignment.objects.get(
            member=self.sai
        )
        remove_selected(self.client, assignment)
        assignment.refresh_from_db()
        self.assertIsNotNone(assignment.revoked_at)
        response = self.client.post(
            admin_url(OrganizerAssignment, 'delete',
                      assignment.pk),
            {'post': 'yes'},
        )
        self.assertEqual(response.status_code, 403)
        self.assertEqual(
            OrganizerAssignment.objects.count(), 2
        )

    def test_rule_messages_reach_the_page(self):
        self.add()
        self.assertContains(
            self.add(),
            'This member already organizes this event.',
        )
        self.assertContains(
            self.add(self.sam),
            'Only members of the Organizers group can '
            'organize events.',
        )

Two of Chapter 23’s tests change in place: Sai joins Organizers before she is added, the event gets a second organizer so that Sai may be removed, and removing uses the action. The message about revoking before an assignment starts has gone from the admin, because nobody types the date any more; the constraint behind it stays.

In config/tests.py, remove from datetime import timedelta and from django.utils import timezone, add Group to the Permission import, replace revoke_form with remove_selected in the events.tests import, and replace the events.models import with:

from audit.models import AuditEvent
from events.models import (
    ORGANIZERS, Event, OrganizerAssignment,
)

In AuditLogTests.setUpTestData(), after Sam’s assignment, add:

        # Chapter 30: the last organizer cannot be removed.
        OrganizerAssignment.objects.create(
            event=cls.event,
            member=User.objects.create_user(
                'raj@example.org', display_name='Raj'
            ),
        )

replace its test_admin_changes_are_logged() with:

    def test_admin_changes_are_logged(self):
        self.edit_location()
        remove_selected(self.client, self.assignment)
        self.assertEqual(
            [(entry.user, entry.action_flag,
              entry.get_change_message())
             for entry in LogEntry.objects.order_by('id')],
            [(self.sam, CHANGE, 'Changed Location.'),
             (self.sam, CHANGE, 'Removed.')],
        )

and add at the end of the file:

class AdministratorAdminTests(TestCase):
    """What an administrator may do in the admin."""

    @classmethod
    def setUpTestData(cls):
        cls.admin = User.objects.create_user(
            'admin@example.org', display_name='Admin',
            is_staff=True,
        )
        cls.admin.groups.add(
            Group.objects.get(name='Administrators')
        )
        cls.soni = User.objects.create_user(
            'soni@example.org', display_name='Soni'
        )
        cls.event = save_event()

    def setUp(self):
        self.client.force_login(self.admin)

    def trail(self):
        """List the audit rows so far: action and outcome."""
        return list(AuditEvent.objects.order_by('id')
                    .values_list('action', 'outcome'))

    def save_soni(self, *groups, **fields):
        """Save Soni's admin page with these groups."""
        return self.client.post(
            admin_url(User, 'change', self.soni.pk),
            {'email': self.soni.email,
             'display_name': 'Soni', 'is_active': 'on',
             'groups': [Group.objects.get(name=name).pk
                        for name in groups]} | fields,
        )

    def test_organizers_membership_is_recorded(self):
        self.save_soni(ORGANIZERS)
        self.save_soni()
        self.assertEqual(self.trail(), [
            ('join_organizers', 'allowed'),
            ('leave_organizers', 'allowed'),
        ])

    def test_an_administrator_cannot_promote_anyone(self):
        response = self.save_soni('Administrators')
        self.assertContains(
            response,
            'Only the Organizers group can be changed here.',
        )
        perm = Permission.objects.get(codename='add_event')
        self.save_soni(is_staff='on', user_permissions=[
            perm.pk])
        self.soni.refresh_from_db()
        self.assertFalse(self.soni.is_staff)
        self.assertFalse(self.soni.user_permissions.exists())

    def test_adds_only_organizers_and_keeps_the_last(self):
        add = admin_url(OrganizerAssignment, 'add')
        form = {'event': self.event.pk,
                'member': self.soni.pk}
        self.assertContains(
            self.client.post(add, form),
            'Only members of the Organizers group',
        )
        self.save_soni(ORGANIZERS)
        self.client.post(add, form)
        place = OrganizerAssignment.objects.get()
        response = remove_selected(self.client, place)
        self.assertContains(
            response, 'Assign another organizer before '
                      'removing the last one.',
        )
        self.assertEqual(self.trail(), [
            ('add_organizer', 'refused'),
            ('join_organizers', 'allowed'),
            ('add_organizer', 'allowed'),
            ('remove_organizer', 'refused'),
        ])

    def test_removal_is_an_action_not_a_typed_date(self):
        place = OrganizerAssignment.objects.create(
            event=self.event, member=self.soni
        )
        page = self.client.get(admin_url(
            OrganizerAssignment, 'change', place.pk
        ))
        self.assertNotContains(page, 'name="revoked_at_0"')
        listing = self.client.get(
            admin_url(OrganizerAssignment, 'changelist')
        )
        self.assertContains(listing,
                            'Remove selected organizers')
uv run python manage.py test config
Found 12 test(s).
Creating test database for alias 'default'...
...
AssertionError: 302 != 200 : Couldn't retrieve content:
    Response code was 302 (expected 200)
AssertionError: 1 != 0 :'name="revoked_at_0"' unexpectedly
    found in the following response
Ran 12 tests in ...s

FAILED (failures=5)
Destroying test database for alias 'default'...
uv run python manage.py test events -k AssignmentAdmin
Found 3 test(s).
Creating test database for alias 'default'...
...
AssertionError: unexpectedly None
AssertionError: 302 != 200 : Couldn't retrieve content:
    Response code was 302 (expected 200)
Ran 3 tests in ...s

FAILED (failures=2)
Destroying test database for alias 'default'...

Now the admin. In events/admin.py, replace the imports below the zoneinfo line with:

from django import forms
from django.contrib import admin, messages
from django.core.exceptions import ValidationError
from django.utils import timezone

from audit.models import AuditEvent, record
from registrations.models import Registration

from .models import (
    Event, OrganizerAssignment, organizer_problem,
)

and replace everything from @admin.register(OrganizerAssignment) to the end with:

class AssignmentForm(forms.ModelForm):
    """The admin's add form, with the page's rules."""

    def clean_member(self):
        """Refuse and record a member who cannot organize."""
        member = self.cleaned_data['member']
        problem = organizer_problem(member)
        if problem:
            event = self.cleaned_data.get('event')
            record(self.request.user,
                   AuditEvent.Action.ADD_ORGANIZER, event,
                   AuditEvent.Outcome.REFUSED,
                   member=member.pk)
            raise ValidationError(problem)
        return member


@admin.register(OrganizerAssignment)
class OrganizerAssignmentAdmin(admin.ModelAdmin):
    """Assign organizers; revoke, but never delete."""

    list_display = ['event', 'member', 'assigned_at',
                    'revoked_at']
    list_filter = [
        ('revoked_at', admin.EmptyFieldListFilter),
    ]
    list_select_related = ['event', 'member']
    form = AssignmentForm
    actions = ['remove_selected']

    def get_fields(self, request, obj=None):
        """Event and member to add; every field after."""
        if obj is None:
            return ['event', 'member']
        return ['event', 'member', 'assigned_at',
                'revoked_at']

    def get_readonly_fields(self, request, obj=None):
        """After adding, every field is read-only."""
        if obj is None:
            return []
        return ['event', 'member', 'assigned_at',
                'revoked_at']

    def get_form(self, request, obj=None, **kwargs):
        """Give the form the request, for its record."""
        form = super().get_form(request, obj, **kwargs)
        form.request = request
        return form

    def save_model(self, request, obj, form, change):
        """Record each organizer added here."""
        super().save_model(request, obj, form, change)
        if not change:
            record(request.user,
                   AuditEvent.Action.ADD_ORGANIZER,
                   obj.event, member=obj.member_id)

    def has_delete_permission(self, request, obj=None):
        """Revoke an assignment instead of deleting it."""
        return False

    @admin.action(description='Remove selected organizers',
                  permissions=['change'])
    def remove_selected(self, request, queryset):
        """Revoke each current assignment chosen."""
        current = queryset.filter(revoked_at__isnull=True)
        for assignment in current.select_related('event'):
            try:
                assignment.revoke(request.user)
            except ValidationError as error:
                self.message_user(
                    request,
                    f'{assignment}: {error.messages[0]}',
                    messages.ERROR,
                )
            else:
                self.log_change(request, assignment,
                                'Removed.')
                self.message_user(
                    request, f'Removed: {assignment}.'
                )

AssignmentForm gives the admin’s add form the same organizer_problem() as the model, and records a refusal. A form has no request of its own, so get_form() gives it one. revoked_at is read-only; removal is the Remove selected organizers action, which calls revoke() for each chosen row and reports each refusal. log_change() keeps Chapter 23’s admin log complete, beside the audit record.

In accounts/admin.py, replace the imports with:

from django import forms
from django.contrib import admin
from django.contrib.admin.models import LogEntry
from django.core.exceptions import ValidationError

from audit.models import AuditEvent, record
from events.models import ORGANIZERS

from .models import User

and replace the UserAdmin class with:

class UserForm(forms.ModelForm):
    """The admin's member form, with its group rule.

    Only a superuser may change groups other than
    Organizers, so no administrator can promote anyone.
    """

    def clean_groups(self):
        """Keep every group but Organizers as it was."""
        groups = self.cleaned_data['groups']
        if self.request.user.is_superuser:
            return groups
        kept = self.instance.groups.exclude(name=ORGANIZERS)
        asked = groups.exclude(name=ORGANIZERS)
        if set(kept) != set(asked):
            raise ValidationError(
                'Only the Organizers group can be changed '
                'here.'
            )
        return groups


@admin.register(User)
class UserAdmin(admin.ModelAdmin):
    """Members' details and access; never passwords."""

    form = UserForm
    list_display = ['email', 'display_name', 'is_staff',
                    'is_active']
    list_filter = ['is_staff', 'is_active']
    search_fields = ['email', 'display_name']
    ordering = ['email']
    fields = ['email', 'display_name', 'is_active',
              'is_staff', 'groups', 'user_permissions',
              'last_login', 'date_joined']
    readonly_fields = ['last_login', 'date_joined']
    filter_horizontal = ['groups', 'user_permissions']

    def get_readonly_fields(self, request, obj=None):
        """Staff flag and permissions: superusers only."""
        if request.user.is_superuser:
            return self.readonly_fields
        return [*self.readonly_fields, 'is_staff',
                'user_permissions']

    def get_form(self, request, obj=None, **kwargs):
        """Give the form the request, for its group rule."""
        form = super().get_form(request, obj, **kwargs)
        form.request = request
        return form

    def has_add_permission(self, request):
        """Members sign up on the site, not here."""
        return False

    def has_delete_permission(self, request, obj=None):
        """Deactivate members instead of deleting them."""
        return False

    def save_related(self, request, form, formsets, change):
        """Record joining or leaving Organizers."""
        member = form.instance
        organizers = member.groups.filter(name=ORGANIZERS)
        before = organizers.exists()
        super().save_related(request, form, formsets, change)
        after = organizers.exists()
        if before != after:
            action = (AuditEvent.Action.JOIN_ORGANIZERS
                      if after else
                      AuditEvent.Action.LEAVE_ORGANIZERS)
            record(request.user, action, member)

UserForm.clean_groups() refuses any change to groups other than Organizers unless a superuser is saving. get_readonly_fields() shows staff status and permissions as plain text to everyone else. save_related() runs after the groups are saved, compares Organizers membership before and after, and records a join or a leave.

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

OK
Destroying test database for alias 'default'...
uv run python manage.py test events -k AssignmentAdmin
Found 3 test(s).
Creating test database for alias 'default'...
...
Ran 3 tests in ...s

OK
Destroying test database for alias 'default'...

Try it: sign in to the admin as admin@example.org. Open Users and Soni, add her to Organizers, and save. Then try adding her to Administrators: the page says “Only the Organizers group can be changed here.” Staff status and permissions are shown but cannot be changed. Under Audit events, the join is the newest row.

While you are on Soni’s page, look at the Groups box. Django’s admin draws it as two boxes, the groups available and the groups chosen, with arrows between them, yet here it is one plain list. An event’s page in the admin has lost something too: the Today and Now shortcuts beside the start and end. The cause is Chapter 24. Its widget templates apply to every form in the project, the admin’s included. Each one writes class="select w-full" (or input, checkbox, textarea) and then includes Django’s attrs.html, which writes the widget’s own class a second time. An element with two class attributes is invalid HTML, and browsers keep only the first, so the admin’s selectfilter class, and the vDateField and vTimeField classes behind the shortcuts, never arrive. A project-wide override reaches pages you did not write, and only a test that looks at those pages notices.

Tests first. Add at the end of config/tests.py:

class WidgetClassTests(TestCase):
    """Otahque's widget classes keep the admin's own."""

    @classmethod
    def setUpTestData(cls):
        cls.sam = User.objects.create_superuser(
            'sam@example.org', display_name='Sam'
        )
        cls.event = save_event()

    def setUp(self):
        self.client.force_login(self.sam)

    def test_the_pickers_keep_selectfilter(self):
        response = self.client.get(
            admin_url(User, 'change', self.sam.pk)
        )
        self.assertContains(
            response, 'class="select w-full selectfilter"',
            count=2,
        )

    def test_event_times_keep_their_shortcuts(self):
        response = self.client.get(
            admin_url(Event, 'change', self.event.pk)
        )
        for name in ('vDateField', 'vTimeField'):
            self.assertContains(
                response, f'class="input w-full {name}"',
                count=2,
            )
uv run python manage.py test config -k WidgetClass
Found 2 test(s).
Creating test database for alias 'default'...
...
Ran 2 tests in ...s

FAILED (failures=2)
Destroying test database for alias 'default'...

The fix is one class attribute holding both: Otahque’s classes first, then the widget’s own. Django’s template language cannot merge two strings into an attribute, so a small template filter does it, a Python function that a template applies with |. Filters live in a templatetags package inside an app. Create an empty events/templatetags/__init__.py, then events/templatetags/otahque_widgets.py:

"""Template filters for Otahque's form widgets."""
from django import template
from django.forms.utils import flatatt

register = template.Library()


@register.filter
def with_class(attrs, classes):
    """Render a widget's attributes with one class attribute.

    Otahque's classes come first, then the widget's own, so
    the admin keeps selectfilter, vDateField, and the rest.
    """
    own = attrs.get('class')
    merged = dict(attrs)
    merged['class'] = f'{classes} {own}' if own else classes
    return flatatt(merged)

flatatt() is the function Django’s own forms use to write a dictionary of attributes: it escapes every value, writes True as a bare attribute such as required, and leaves out False and None, as attrs.html does. {% load otahque_widgets %} makes the filter available in a template. Replace templates/django/forms/widgets/input.html with:

{% load otahque_widgets %}
<input type="{{ widget.type }}" name="{{ widget.name }}"
       {% if widget.value != None %}
       value="{{ widget.value|stringformat:'s' }}"{% endif %}
       {{ widget.attrs|with_class:"input w-full" }}>

templates/django/forms/widgets/checkbox.html with:

{% load otahque_widgets %}
<input type="{{ widget.type }}" name="{{ widget.name }}"
       {% if widget.value != None %}
       value="{{ widget.value|stringformat:'s' }}"{% endif %}
       {{ widget.attrs|with_class:"checkbox" }}>

and templates/django/forms/widgets/textarea.html with:

{% load otahque_widgets %}
<textarea name="{{ widget.name }}"
          {{ widget.attrs|with_class:"textarea w-full" }}>
{% if widget.value %}{{ widget.value }}{% endif %}</textarea>

In templates/django/forms/widgets/select.html, replace the first two lines, up to the > that closes the select tag, with:

{% load otahque_widgets %}
<select name="{{ widget.name }}"
        {{ widget.attrs|with_class:"select w-full" }}>
uv run python manage.py test config -k WidgetClass
Found 2 test(s).
Creating test database for alias 'default'...
...
Ran 2 tests in ...s

OK
Destroying test database for alias 'default'...

Otahque’s own pages look exactly as before, because none of their widgets sets a class; Chapter 24’s markup tests still count class="input w-full". Reload Soni’s page in the admin: Groups is two boxes again, and an event’s page has its shortcuts. Finally, add at the end of docs/design/event-draft-form.md:

- Fixed in Chapter 30: each widget writes one class
  attribute, Otahque's classes first, then the widget's
  own (the with_class filter), so the admin keeps its
  selectfilter and date and time shortcuts.

Step 9: The Organizer access page

Administrators also get a page of Otahque’s own, where each event’s organizers are listed, added, and removed, without the admin’s general tools. It must open for nobody else. Tests first. Add after the finders import of events/tests.py:

from django.core.cache import cache

and at the end of the file:

class OrganizerPageTests(TestCase):
    """The organizers page: who may use it, and rules."""

    @classmethod
    def setUpTestData(cls):
        cls.admin = in_group(
            'admin@example.org', 'Administrators',
            is_staff=True,
        )
        cls.sam = in_group('sam@example.org', ORGANIZERS)
        cls.soni = in_group('soni@example.org', ORGANIZERS)
        cls.event = future_draft(cls.sam)
        cls.url = action_url('organizers', cls.event)
        cls.remove = action_url('remove_organizer',
                                cls.event)

    def setUp(self):
        cache.clear()

    def confirm(self, user):
        """Sign in, then confirm the password.

        allauth asks for it before a change on this page.
        """
        self.client.force_login(user)
        self.client.post(reverse('account_reauthenticate'),
                         {'password': SAI_PASSWORD})

    def place(self, user, event=None):
        """Return user's assignment to event, or to ours."""
        event = event or self.event
        return event.organizer_assignments.get(member=user)

    def test_a_visitor_is_sent_to_sign_in(self):
        self.assertRedirects(
            self.client.get(self.url),
            f"{reverse('account_login')}?next={self.url}",
            fetch_redirect_response=False,
        )

    def test_others_get_403_and_are_recorded(self):
        for user in (self.sam, member('sai@example.org')):
            self.client.force_login(user)
            with self.subTest(user=user.email):
                for response in (
                    self.client.get(self.url),
                    self.client.get(
                        reverse('events:organizer_events')),
                    self.client.post(self.remove, {}),
                ):
                    self.assertEqual(
                        response.status_code, 403
                    )
        refused = AuditEvent.objects.filter(
            action='manage_organizers', outcome='refused'
        )
        self.assertEqual(refused.count(), 6)

    def test_changes_need_a_recent_sign_in(self):
        self.client.force_login(self.admin)
        self.assertContains(self.client.get(self.url),
                            'Add an organizer')
        response = self.client.post(
            self.url, {'email': self.soni.email}
        )
        self.assertTrue(response.url.startswith(
            reverse('account_reauthenticate')))
        self.assertFalse(self.event.has_organizer(self.soni))

    def test_an_administrator_adds_an_organizer(self):
        self.confirm(self.admin)
        response = self.client.post(
            self.url, {'email': 'SONI@example.org'}
        )
        self.assertRedirects(response, self.url)
        self.assertTrue(self.event.has_organizer(self.soni))

    def test_the_page_refuses_what_the_rules_refuse(self):
        member('sai@example.org')
        self.confirm(self.admin)
        for email, message in [
            ('sai@example.org', 'Only members of the '
                                'Organizers group'),
            ('nobody@example.org', 'No member has this'),
            ('sam@example.org', 'already organizes'),
        ]:
            with self.subTest(email=email):
                self.assertContains(self.client.post(
                    self.url, {'email': email}), message)

    def test_remove_one_but_keep_the_last(self):
        self.event.grant_organizer(self.soni, self.admin)
        self.confirm(self.admin)
        for user, message in [
            (self.soni, 'Organizer removed.'),
            (self.sam, 'Assign another organizer before '
                       'removing the last one.'),
        ]:
            response = self.client.post(self.remove, {
                'assignment': self.place(user).pk,
            }, follow=True)
            self.assertContains(response, message)
        self.assertTrue(self.event.has_organizer(self.sam))

    def test_another_events_organizer_is_not_a_choice(self):
        swap = future_draft(self.soni, title='Book swap')
        self.confirm(self.admin)
        response = self.client.post(self.remove, {
            'assignment': self.place(self.soni, swap).pk,
        })
        self.assertEqual(response.status_code, 404)
        self.assertTrue(swap.has_organizer(self.soni))

    def test_the_list_runs_a_fixed_number_of_queries(self):
        for title in ('Book swap', 'Delhi clinic'):
            future_draft(self.soni, title=title)
        self.client.force_login(self.admin)
        url = reverse('events:organizer_events')
        with self.assertNumQueries(7):
            self.client.get(url)

confirm() signs in and then confirms the password on allauth’s re-authentication page, because a change here asks for it. cache.clear() resets allauth’s rate limits between tests, as Chapter 29 explained.

uv run python manage.py test events.tests.OrganizerPageTests
Found 8 test(s).
Creating test database for alias 'default'...
...
Ran 0 tests in ...s

FAILED (errors=1)
Destroying test database for alias 'default'...

The one error is in setUpTestData(), before any test runs: NoReverseMatch: Reverse for 'organizers' not found, because the page has no address yet. Two forms first. In events/forms.py, add from django.contrib.auth import get_user_model after from django import forms, and at the end:

class OrganizerForm(forms.Form):
    """An administrator names a member by email."""

    email = forms.EmailField(
        label='Member’s email address'
    )

    def clean_email(self):
        """Find the member with this email, or refuse."""
        email = self.cleaned_data['email'].lower()
        User = get_user_model()
        try:
            self.member = User.objects.get(email=email)
        except User.DoesNotExist:
            raise ValidationError(
                'No member has this email address.'
            ) from None
        return email


class RemoveOrganizerForm(forms.Form):
    """Which current organizer of this event to remove.

    Choices from other events are not valid.
    """

    assignment = forms.ModelChoiceField(queryset=None)

    def __init__(self, *args, event, **kwargs):
        """Offer only this event's current organizers."""
        super().__init__(*args, **kwargs)
        current = event.organizer_assignments.filter(
            revoked_at__isnull=True
        )
        self.fields['assignment'].queryset = current

OrganizerForm finds a member by email, in lower case, as Chapter 21 stores them. RemoveOrganizerForm accepts only a current assignment of this event: its choices come from the event’s own assignments, so a number belonging to another event is not a valid choice and the page answers 404. That is OWASP’s advice against IDOR, a lookup scoped to what the request may touch, built into the form.

In events/views.py, replace the imports with:

from functools import wraps

from allauth.account.decorators import (
    reauthentication_required,
)
from django.contrib import messages
from django.contrib.auth.decorators import (
    login_required, permission_required,
)
from django.core.exceptions import (
    PermissionDenied, ValidationError,
)
from django.db import models, transaction
from django.http import Http404
from django.shortcuts import (
    get_object_or_404, redirect, render,
)
from django.utils import timezone
from django.views.decorators.http import (
    require_http_methods, require_POST,
)

from audit.models import AuditEvent, record

from .forms import (
    CopyForm, EventForm, OrganizerForm, RemoveOrganizerForm,
)
from .models import Event, OrganizerAssignment

and add after them:

Action = AuditEvent.Action


def deny(request, action, event=None, hidden=False):
    """Record a refused attempt, then refuse it.

    Only a signed-in person's attempt is recorded. The answer
    is 404 if the event is hidden, else 403.
    """
    if request.user.is_authenticated:
        record(request.user, action, event,
               AuditEvent.Outcome.REFUSED)
    if hidden:
        raise Http404('No event matches the given query.')
    raise PermissionDenied

deny() is the one place a refusal happens: it records the attempt if someone is signed in, then raises 404 or 403. Step 10 sends the event pages through it as well. Add the three views at the end of the file:

def organizer_access(view):
    """Allow only holders of events.manage_organizers.

    Anyone else gets 403, and the attempt is recorded.
    """
    @wraps(view)
    def wrapper(request, *args, **kwargs):
        if not request.user.has_perm(
                'events.manage_organizers'):
            deny(request, Action.MANAGE_ORGANIZERS)
        return view(request, *args, **kwargs)
    return wrapper


@login_required
@organizer_access
def organizer_events(request):
    """Every event with its current organizers."""
    current = OrganizerAssignment.objects.filter(
        revoked_at__isnull=True
    ).select_related('member')
    events = Event.objects.order_by(
        '-starts_at'
    ).prefetch_related(models.Prefetch(
        'organizer_assignments', queryset=current,
        to_attr='current_organizers',
    ))
    return render(request, 'events/organizer_events.html',
                  {'events': events})


@login_required
@organizer_access
@reauthentication_required(allow_get=True)
def event_organizers(request, event_id):
    """List an event's organizers; add one by email."""
    event = get_object_or_404(Event, pk=event_id)
    form = OrganizerForm(request.POST or None)
    if form.is_valid():
        try:
            event.grant_organizer(form.member, request.user)
        except ValidationError as error:
            form.add_error('email', error)
        else:
            messages.success(request, 'Organizer added.')
            return redirect('events:organizers', event.pk)
    # Current organizers first, on SQLite and PostgreSQL.
    assignments = event.organizer_assignments.order_by(
        models.F('revoked_at').asc(nulls_first=True),
        'assigned_at',
    ).select_related('member')
    return render(request, 'events/organizers.html', {
        'event': event,
        'form': form,
        'assignments': assignments,
    })


@require_POST
@login_required
@organizer_access
@reauthentication_required
def remove_organizer(request, event_id):
    """Remove one current organizer, if allowed."""
    event = get_object_or_404(Event, pk=event_id)
    form = RemoveOrganizerForm(request.POST, event=event)
    if not form.is_valid():
        raise Http404('No current organizer matches.')
    try:
        form.cleaned_data['assignment'].revoke(request.user)
    except ValidationError as error:
        refuse(request, error)
    else:
        messages.success(request, 'Organizer removed.')
    return redirect('events:organizers', event.pk)

organizer_access is a small decorator of Otahque’s own. Django’s permission_required would refuse too, but before Otahque’s code runs, so it could not record the attempt. The order of the decorators is the order of the checks: signed in, then the permission, then re-authentication, so that someone without the permission is never asked for a password. reauthentication_required(allow_get=True) lets an administrator read the page freely, and asks for the password before any POST. organizer_events fetches each event’s current organizers with one prefetch, so the list costs the same number of queries for three events or three hundred.

In events/urls.py, add after the copy path:

    path('events/organizers/', views.organizer_events,
         name='organizer_events'),
    path('events/<int:event_id>/organizers/',
         views.event_organizers, name='organizers'),
    path('events/<int:event_id>/organizers/remove/',
         views.remove_organizer, name='remove_organizer'),

Create events/templates/events/organizer_events.html:

{% extends "base.html" %}

{% block title %}Organizer access | Otahque{% endblock %}

{% block content %}
  <h1>Organizer access</h1>
  <p>Every event, newest first, with its current
     organizers. Open one to add or remove an organizer.</p>
  <ul class="event-list space-y-3">
    {% for event in events %}
      <li class="event-row card border border-base-300
                 bg-base-100 p-4">
        <p>
          <a class="font-semibold"
             href="{% url 'events:organizers' event.pk %}">
            {{ event.title }}</a>
          <span class="badge badge-outline">
            {{ event.get_status_display }}</span>
        </p>
        <p class="text-sm">
          {% for organizer in event.current_organizers %}
            {% if not forloop.first %}·{% endif %}
            {{ organizer.member.display_name }}
          {% empty %}
            No current organizer
          {% endfor %}
        </p>
      </li>
    {% empty %}
      <li class="event-empty card border border-base-300
                 bg-base-100 p-4">
        There are no events yet.</li>
    {% endfor %}
  </ul>
{% endblock %}

and events/templates/events/organizers.html:

{% extends "base.html" %}

{% block title %}Organizers of {{ event.title }} |
  Otahque{% endblock %}

{% block content %}
  {% url 'events:remove_organizer' event.pk as remove_url %}
  <h1>Organizers of {{ event.title }}</h1>
  <p><a href="{% url 'events:organizer_events' %}">
    All events</a></p>
  <ul class="space-y-3">
    {% for assignment in assignments %}
      <li class="card border border-base-300 bg-base-100
                 p-4">
        <p class="font-semibold">
          {{ assignment.member.display_name }}</p>
        <p class="text-sm">{{ assignment.member.email }}</p>
        {% if assignment.revoked_at %}
          <p class="text-sm">Removed
            {{ assignment.revoked_at|date:"j M Y, H:i" }}</p>
        {% else %}
          <form method="post" action="{{ remove_url }}">
            {% csrf_token %}
            <button type="submit" name="assignment"
                    value="{{ assignment.pk }}"
                    class="btn btn-outline btn-sm">
              Remove</button>
          </form>
        {% endif %}
      </li>
    {% empty %}
      <li class="card border border-base-300 bg-base-100
                 p-4">This event has no organizers.</li>
    {% endfor %}
  </ul>
  <h2>Add an organizer</h2>
  <p>The member must be active and in the Organizers
     group, which the admin site sets.</p>
  <form method="post" class="card space-y-4 border
        border-base-300 bg-base-100 p-6">
    {% csrf_token %}
    {{ form }}
    <button type="submit" class="btn btn-primary">
      Add organizer</button>
  </form>
{% endblock %}

Each Remove button sends its assignment’s number as the value of assignment; one address serves every row. An administrator’s menu now has six items, more than a 390 px phone can show in one row, so in templates/includes/site_nav.html let it wrap, by adding flex-wrap to the nav element’s classes:

<nav class="site-nav navbar flex-wrap gap-5 bg-neutral
            px-4 text-neutral-content" aria-label="Site">

and add after the New event link:

  {% if perms.events.manage_organizers %}
    <a href="{% url 'events:organizer_events' %}">
      Organizer access</a>
  {% endif %}
uv run python manage.py test events.tests.OrganizerPageTests
Found 8 test(s).
Creating test database for alias 'default'...
...
Ran 8 tests in ...s

OK
Destroying test database for alias 'default'...

Try it: signed in as admin@example.org, choose Organizer access in the menu, open one of Sam’s events, and add soni@example.org. Otahque asks for your password first, even though you have just signed in: allauth counts only a confirmation, not the sign-in itself, and then trusts it for five minutes. Remove Sam, then try to remove Soni: “Assign another organizer before removing the last one.” Sign in as Soni in another browser: her menu has My events and New event but no Organizer access, and typing its address gives 403. Sam would see the link, because a superuser holds every permission, which is one more reason he is not a daily account.

Step 10: Record each action and each refusal

Tests first, at the end of events/tests.py:

class AuditTrailTests(TestCase):
    """Each action leaves the right audit rows."""

    @classmethod
    def setUpTestData(cls):
        cls.sam = in_group('sam@example.org', ORGANIZERS)
        cls.raj = in_group('raj@example.org', ORGANIZERS)

    def trail(self):
        """List the audit rows so far: action and outcome."""
        return list(AuditEvent.objects.order_by('id')
                    .values_list('action', 'outcome'))

    def test_each_event_action_is_recorded(self):
        self.client.force_login(self.sam)
        self.client.post(reverse('events:create'), NEW_EVENT)
        clinic = Event.objects.get(title=NEW_EVENT['title'])
        self.client.post(edit_url(clinic),
                         as_sent(clinic, location='Room 2'))
        event = future_draft(self.sam)
        for name in ('publish', 'cancel'):
            self.client.post(action_url(name, event))
        self.client.post(action_url('copy', event),
                         {'starts_at': '2027-02-04T19:00'})
        copy = Event.objects.latest('pk')
        self.client.post(action_url('delete', copy))
        self.assertEqual(self.trail(), [
            (action, 'allowed') for action in (
                'create_event', 'edit_event',
                'publish_event', 'cancel_event',
                'copy_event', 'delete_event',
            )
        ])
        edit = AuditEvent.objects.get(action='edit_event')
        self.assertEqual(edit.detail,
                         {'fields': ['location']})

    def test_refusals_by_members_are_recorded(self):
        draft = future_draft(self.sam)
        published = future_draft(
            self.sam, status='published'
        )
        self.client.get(draft.get_absolute_url())
        self.client.force_login(self.raj)
        self.client.get(draft.get_absolute_url())
        self.client.get(edit_url(draft))
        self.client.post(action_url('cancel', published))
        self.client.force_login(member('sai@example.org'))
        self.client.get(reverse('events:create'))
        self.assertEqual(self.trail(), [
            ('view_event', 'refused'),
            ('edit_event', 'refused'),
            ('cancel_event', 'refused'),
            ('create_event', 'refused'),
        ])

    def test_a_rule_or_an_unknown_event_adds_nothing(self):
        draft = future_draft(self.sam, description='')
        self.client.force_login(self.sam)
        self.client.post(action_url('publish', draft))
        self.client.get(reverse('events:edit', args=[999]))
        self.assertEqual(self.trail(), [])
uv run python manage.py test events.tests.AuditTrailTests
Found 3 test(s).
Creating test database for alias 'default'...
...
AssertionError: Lists differ: [] != [('create_event',
    'allowed'), ('edit_event[124 chars]ed')]
AssertionError: Lists differ: [] != [('view_event',
    'refused'), ('edit_event',[65 chars]ed')]
Ran 3 tests in ...s

FAILED (failures=2)
Destroying test database for alias 'default'...

The rule-breaking test already passes, because nothing is recorded yet anywhere; the other two fail. In events/views.py, add from django.forms.models import model_to_dict after the django.db import. Then replace event_detail() and event_create(), with its decorators, by:

def event_detail(request, event_id):
    """Show an event its viewer may see, or 404."""
    event = get_object_or_404(
        Event.objects.with_places(), pk=event_id
    )
    if not event.is_visible_to(request.user):
        deny(request, Action.VIEW_EVENT, event, hidden=True)
    return render(request, 'events/detail.html', {
        'event': event,
        'now': timezone.now(),
        'can_edit': event.can_be_edited_by(request.user),
    })


@login_required
def event_create(request):
    """Create an event, for members who may add events."""
    if not request.user.has_perm('events.add_event'):
        deny(request, Action.CREATE_EVENT)
    if request.method == 'POST':
        form = EventForm(request.POST)
        if form.is_valid():
            with transaction.atomic():
                event = form.save()
                event.add_organizer(request.user)
                record(request.user, Action.CREATE_EVENT,
                       event)
            messages.success(request, 'Draft saved.')
            return redirect(event)
    else:
        form = EventForm()
    return render(request, 'events/form.html',
                  {'form': form})

event_create() loses its @permission_required decorator: the same check is now inside, through deny(), so the attempt is recorded. Replace event_to_manage() and event_edit() with:

def event_to_manage(request, event_id, action):
    """Return the event, if this member may change it.

    A refusal is recorded as an attempt at action.
    """
    event = get_object_or_404(Event, pk=event_id)
    if not event.is_visible_to(request.user):
        deny(request, action, event, hidden=True)
    if not event.can_be_edited_by(request.user):
        deny(request, action, event)
    return event


@login_required
def event_edit(request, event_id):
    """Edit the event, for those who may change it."""
    event = event_to_manage(request, event_id,
                            Action.EDIT_EVENT)
    title = event.title
    if request.method == 'POST':
        before = model_to_dict(event)
        form = EventForm(request.POST, instance=event)
        if form.is_valid():
            with transaction.atomic():
                form.save()
                after = model_to_dict(event)
                changed = [name for name in form.fields
                           if before[name] != after[name]]
                record(request.user, Action.EDIT_EVENT,
                       event, fields=changed)
            messages.success(request, 'Changes saved.')
            return redirect(event)
    else:
        form = EventForm(instance=event)
    return render(request, 'events/edit.html', {
        'form': form,
        'title': title,
        'event_id': event.pk,
        'taken': event.places_taken(),
    })

event_to_manage() now takes the action being attempted, so a refusal is recorded as what it was: an attempt to edit, publish, cancel, delete, or copy. The edit records which fields changed by comparing the saved values before and after, for the reason the Common Error below explains. Replace event_publish() and event_cancel() with:

def event_publish(request, event_id):
    """Publish the event, or say why not."""
    event = event_to_manage(request, event_id,
                            Action.PUBLISH_EVENT)
    try:
        with transaction.atomic():
            event.publish()
            record(request.user, Action.PUBLISH_EVENT,
                   event)
    except ValidationError as error:
        refuse(request, error)
    else:
        messages.success(request, 'Published.')
    return redirect(event)


@require_POST
@login_required
def event_cancel(request, event_id):
    """Cancel the event, or say why not."""
    event = event_to_manage(request, event_id,
                            Action.CANCEL_EVENT)
    try:
        with transaction.atomic():
            event.cancel()
            record(request.user, Action.CANCEL_EVENT,
                   event)
    except ValidationError as error:
        refuse(request, error)
    else:
        messages.success(request, 'Event cancelled.')
    return redirect(event)

and event_delete() and event_copy() with:

def event_delete(request, event_id):
    """Confirm, then delete a draft; or say why not."""
    event = event_to_manage(request, event_id,
                            Action.DELETE_EVENT)
    if request.method == 'POST':
        try:
            with transaction.atomic():
                # Recorded first: deleting clears event.pk.
                record(request.user, Action.DELETE_EVENT,
                       event, title=event.title)
                event.delete_draft()
        except ValidationError as error:
            refuse(request, error)
            return redirect(event)
        messages.success(request, 'Draft deleted.')
        return redirect('events:manage')
    if event.status != Event.Status.DRAFT:
        refuse(request, ValidationError(
            'Only a draft can be deleted.'
        ))
        return redirect(event)
    return render(request, 'events/delete.html',
                  {'event': event})


@require_http_methods(['GET', 'POST'])
@login_required
def event_copy(request, event_id):
    """Ask for a start, then copy the event as a draft."""
    event = event_to_manage(request, event_id,
                            Action.COPY_EVENT)
    if request.method == 'POST':
        form = CopyForm(request.POST, event=event)
        if form.is_valid():
            with transaction.atomic():
                copy = event.copy_as_draft(
                    request.user,
                    form.cleaned_data['starts_at'],
                )
                record(request.user, Action.COPY_EVENT,
                       copy, source=event.pk)
            messages.success(
                request, 'Copied as a new draft.'
            )
            return redirect('events:edit', copy.pk)
    else:
        form = CopyForm(event=event)
    return render(request, 'events/copy.html',
                  {'event': event, 'form': form})

Each action and its record share a transaction. When publish() refuses a draft with no description, it raises before saving, the transaction rolls back, and no record remains: the trail never says something happened that did not. The delete records first, because deleting a row clears its pk, and the record needs the number.

uv run python manage.py test events.tests.AuditTrailTests
Found 3 test(s).
Creating test database for alias 'default'...
...
Ran 3 tests in ...s

OK
Destroying test database for alias 'default'...

Common Error: an edit that changed only the location records the times too

Django’s form.changed_data compares what was typed with what the form first showed, field by field. EventForm shows times in the event’s own zone and reads them back in that zone in its own clean(), but each field’s change check sees only the typed time and the stored time in UTC, so for any event outside UTC it reports starts_at and ends_at as changed when they were not. Recording changed_data would fill the trail with changes nobody made. Compare the saved values instead, as event_edit() does with model_to_dict().

Try it: sign in as Soni and type the address of a draft she does not organize. Then, as the administrator, open Audit events in the admin and filter by outcome: Soni’s refused view_event is there, with her account and the draft’s number.

Step 11: Write the design down

Create docs/design/permissions.md:

# Who may do what: permissions and roles

Status: Drafted in Chapter 30, for review. Not approved.
Rules: PR-4 (organizers manage only assigned events),
PR-5 (publication), PR-6 (only the administrator grants
or removes organizer access). Decision: ADR-004.

## Two questions, two places

1. May this person organize at all? Membership of the
   Organizers group (add_event, change_event), set by
   the administrator in the admin.
2. Do they organize this event? A current
   OrganizerAssignment, added or removed by the
   administrator, on the admin or the Organizer access
   page.

Editing, publishing, cancelling, deleting, and copying
need both (Event.can_be_edited_by). An inactive account
answers no to both (Event.has_organizer).

## Roles

- Visitor: published and cancelled events only.
- Member: the same; their own account pages.
- Organizer: Organizers group; manages assigned events.
- Administrator: Administrators group, a staff account
  per person. The admin pages for accounts, assignments,
  events, registrations (view), and both logs; the
  Organizer access page (events.manage_organizers).
  Manages no event on Otahque's own pages; changes no
  group except Organizers.
- Superuser: every permission; a local setup tool only.
- Staff only: may open the admin; sees nothing there.

## Matrix: Sam's draft

| Person          | View | Edit    | Publish | Create  |
|-----------------|------|---------|---------|---------|
| Visitor         | 404  | sign in | sign in | sign in |
| Member          | 404  | 404     | 404     | 403     |
| Staff only      | 404  | 404     | 404     | 403     |
| Other organizer | 404  | 404     | 404     | ok      |
| Administrator   | ok   | 403     | 403     | 403     |
| Superuser       | ok   | 403     | 403     | ok      |
| Organizer       | ok   | ok      | ok      | ok      |

A published event shows to everyone, so a refused change
there is 403, not 404. Proved by PermissionMatrixTests.

## Refusals

- Hidden event: 404, so its number reveals nothing.
- Visible but not theirs: 403.
- Signed out: sent to sign in.
- A signed-in refusal is recorded as a refused
  AuditEvent; an unknown number is not.

## Organizer access

- Added only for active members of Organizers.
- The last current organizer of a draft or published
  event is not removed; a cancelled event may lose all.
- Add and Remove on the Organizer access page ask for
  the password again (allauth re-authentication, five
  minutes). The admin does not yet: Chapter 59.

## Audit

AuditEvent (app audit): actor, action, outcome (allowed
or refused), target, detail (field names, member ids),
time. Written in the action's own transaction. Rows are
ordinary database rows, not tamper-proof. Retention,
redaction, and alerts: Chapter 65.

## Planned rows

- Chapter 31: members' own registrations; an organizer's
  attendee list (PR-1, PR-4).
- Chapter 46: check-in by assigned organizers; a token
  never replaces these checks.
- Chapter 50: the same rules behind the API.
- Chapter 70: volunteers, a role separate from
  organizers.

and docs/adr/ADR-004-access-rules.md, the decision record for where the rules live:

# ADR-004: Access rules in model methods and groups

## Status

Proposed, November 2026 (Chapter 30). The choice follows
the user's decisions of 18 November 2026 (Chapter 30
P2-P4); this record is not yet reviewed or accepted.

## Context

Otahque must answer "may this person do this to this
event?" on every page, in the admin, and later in the API.
The answer depends on a role (may organize) and on a
relationship (organizes this event). Django's model
permissions are per model, not per event, and its
ModelBackend returns no permissions for an object.

## Options

- A: model methods on Event (has_organizer,
  is_visible_to, can_be_edited_by), with Django groups
  for roles; every view calls one method.
- B: policy functions in a separate module.
- C: django-rules: predicates behind
  user.has_perm(perm, event).
- D: django-guardian: a permission row per member and
  event.

## Decision

Option A. Groups Organizers and Administrators are
created by a migration; events.manage_organizers guards
the Organizer access page.

## Consequences

- One place to read and test each rule; the matrix in
  docs/design/permissions.md has a test per row.
- has_perm(perm, obj) is not used: Django answers True
  for any active superuser before a backend is asked, so
  C would let every superuser manage every event.
- D would repeat OrganizerAssignment as permission rows.
- Changing a group's permissions needs a migration until
  Chapter 41 adds a command.

## Revisit when

- The API (Chapter 50) needs the rules in a shared
  module (option B).
- Communities (Chapters 67-68) make organizing rights
  per community.

In docs/design/admin.md, replace the items for organizer assignments and users with:

- Organizer assignments: view, add (active members of
  Organizers only), and remove with the Remove selected
  organizers action, which keeps the last organizer of a
  live event; never deleted (PR-6). Chapter 30.
- Users: view and change email, display name, active,
  staff, groups, and permissions. An administrator who is
  not a superuser changes only Organizers membership;
  staff and permissions are read-only (Chapter 30). No
  add page (accounts come from createsuperuser or
  create_user until Chapter 27), no delete (deactivate
  instead), and the password is never shown or set here.

replace the first item under “What the admin does not protect” with:

- The admin log records admin saves only: not the
  shell, scripts, migrations, Otahque's own pages, or
  sign-ins. Its rows can be changed by anyone with
  database access. Business audit trail: AuditEvent from
  Chapter 30, completed in Chapter 65.

and the “Planned (Chapter 30)” best practice with:

- Done (Chapter 30): an Administrators group with only
  the permissions the role needs, one staff account per
  person; no shared superuser accounts.

In docs/design/event-states.md, replace the “Who may act” lines below the status with:

Who may act: current organizers who hold events.change_event
(Event.can_be_edited_by, Chapter 25), through the Organizers
group since Chapter 30; see permissions.md.

and the open item about audit records with:

- Done (Chapter 30): each move, and each refused attempt,
  is an AuditEvent.

Step 12: Check and commit

uv run python manage.py makemigrations --check --dry-run
No changes detected
uv run python manage.py test
Found 288 test(s).
Creating test database for alias 'default'...
...
Ran 288 tests in ...s

OK
Destroying test database for alias 'default'...
git add .
git status --short
git commit -m "Add roles, organizer access, and an audit trail"
M  accounts/admin.py
A  accounts/migrations/0004_groups.py
M  accounts/tests.py
A  audit/__init__.py
A  audit/admin.py
A  audit/apps.py
A  audit/migrations/0001_initial.py
A  audit/migrations/__init__.py
A  audit/models.py
A  audit/tests.py
A  audit/views.py
M  config/settings.py
M  config/tests.py
A  docs/adr/ADR-004-access-rules.md
M  docs/design/admin.md
M  docs/design/event-draft-form.md
M  docs/design/event-states.md
A  docs/design/permissions.md
M  events/admin.py
M  events/forms.py
A  events/migrations/0005_manage_organizers.py
M  events/models.py
A  events/templates/events/organizer_events.html
A  events/templates/events/organizers.html
A  events/templatetags/__init__.py
A  events/templatetags/otahque_widgets.py
M  events/tests.py
M  events/urls.py
M  events/views.py
M  templates/django/forms/widgets/checkbox.html
M  templates/django/forms/widgets/input.html
M  templates/django/forms/widgets/select.html
M  templates/django/forms/widgets/textarea.html
M  templates/includes/site_nav.html

Table 30.2 lists what to do when a step does not go as described.

Table 30.2 — When a step goes wrong
Symptom Likely cause Recovery
cannot import name 'AuditEvent' audit/models.py still the generated file Replace it with the Step 2 listing
no such table: audit_auditevent The audit migration not made or not applied makemigrations audit, then migrate
Permission matching query does not exist The create_permissions() loop left out Restore the loop in 0004_groups.py
A test adds a group and still gets 403 The user object kept its cached permissions Fetch the user again before asking
Organizer access missing from the menu The account is not in Administrators Add it to the group as Sam, in the admin
Add or Remove goes to a password page Re-authentication, as designed Confirm the password; it lasts five minutes
"Only the Organizers group can be changed here." An administrator changed another group Ask a superuser to make that change
Audit records show times that did not change changed_data used for the record Compare model_to_dict() before and after
PAGE 003

Verify Your Work

Work through Table 30.3 from the folder that holds manage.py. For the browser rows, start the development server and use a private window for each person, so that no earlier session is sent.

Table 30.3 — Verification checklist for Chapter 30
Check Command or action Expected result
Starting point uv run python manage.py test Found 257 test(s); OK
Tests fail first Each step's new tests, before the code FAILED, ImportError, or NoReverseMatch
Tests pass uv run python manage.py test Found 288 test(s); OK
No migration waiting makemigrations --check --dry-run No changes detected
Groups exist Admin, Groups, as Sam Administrators and Organizers, with the Step 4 permissions
Organizer creates Soni, in Organizers, opens New event The form opens; her draft lists her as organizer
IDOR refused Soni types a draft's address she does not organize Page not found
Organizer access admin@example.org, menu, Organizer access Every event and its current organizers
Re-authentication Add an organizer Password asked first, then "Organizer added."
Last organizer Remove an event's only organizer "Assign another organizer before removing the last one."
No promotion Admin, a user, add Administrators, as admin@example.org "Only the Organizers group can be changed here."
Others refused Soni opens /events/organizers/ 403 Forbidden
Audit trail Admin, Audit events, filter Refused Soni's refused attempt with her account
Phone width Device toolbar, 390 px No sideways scroll on the two Organizer access pages
Committed git status --short No output
Not verified macOS, Linux, WSL; Firefox, Safari Readers on those systems

The commands were checked in Windows PowerShell 5.1 and Git Bash, from a copy of the Chapter 29 checkpoint, with each listing applied in the order printed. The browser rows were walked through in Microsoft Edge at 390 px and 1280 px.

PAGE 004

Checkpoint: Quiz and Challenge

Quiz

Que. 3 Sam is staff and a superuser. Which of Otahque’s roles does that give him?

Flip to check your answerFold answer back

Answer. None by itself. is_staff only opens the admin, and is_superuser holds every Django permission. Otahque’s organizer role needs an assignment to each event, and its administrator role is the Administrators group. Sam organizes his events because he is assigned to them.

Que. 4 Why does Otahque create its groups in a migration instead of in the admin?

Flip to check your answerFold answer back

Answer. So that every database gets exactly the same groups: yours, every reader’s, the test database, and the deployed one. A test then checks their permissions exactly. Groups made by hand in the admin exist only where someone made them.

Que. 5 Why does Otahque not use user.has_perm('events.change_event', event)?

Flip to check your answerFold answer back

Answer. Django’s ModelBackend returns no permissions for an object, so it would always say no, and has_perm() says yes to any active superuser before a backend is asked. Otahque’s rule is in Event.can_be_edited_by(), which asks for the permission and a current assignment, the same questions for everyone.

Que. 6 When does Otahque answer 404, and when 403?

Flip to check your answerFold answer back

Answer. 404 when the person may not see the event at all, such as someone else’s draft, so the refusal reveals nothing. 403 when they may see it but not change it, such as someone else’s published event. A visitor who is not signed in is sent to sign in.

Que. 7 Publishing a draft with no description fails. What does the audit trail record?

Flip to check your answerFold answer back

Answer. Nothing. The rule refuses before anything is saved, and the record shares the action’s transaction, so it is rolled back too. The trail records refused attempts at access, not a member’s mistakes; the message on the page tells them what to fix.

Mini-Challenge

Que. 8 Raj, an organizer of his own event, opens the edit page of Sam’s draft, then of Sam’s published meetup. Predict the two answers and what the audit trail records, then check with l2_predict.py below, run with uv run python manage.py shell -c "exec(open('l2_predict.py').read())".

Flip to check your answerFold answer back

Answer. The draft answers 404: Raj may not see it, so it is treated as if it did not exist. The published meetup answers 403: anyone may see it, but Raj does not organize it. Both attempts are recorded as refused edit_event rows naming Raj. The file undoes its work, so your rows are unchanged:

import logging
from datetime import timedelta

from django.contrib.auth.models import Group
from django.db import transaction
from django.test import Client
from django.test.utils import setup_test_environment
from django.utils import timezone

from accounts.models import User
from audit.models import AuditEvent
from events.models import Event

setup_test_environment()
# Quieten Django's warnings: the status codes say enough.
logging.disable(logging.WARNING)
with transaction.atomic():
    organizers = Group.objects.get(name='Organizers')
    sam, raj = [
        User.objects.create_user(f'{name}.demo@example.org',
                                 display_name=name)
        for name in ('sam', 'raj')
    ]
    for person in (sam, raj):
        person.groups.add(organizers)
    start = timezone.now() + timedelta(days=7)
    events = [
        Event.objects.create(
            title=title, status=status, starts_at=start,
            ends_at=start + timedelta(hours=2),
            timezone='UTC', location='Leeds', capacity=20)
        for title, status in (('Sam draft', 'draft'),
                              ('Sam meetup', 'published'))
    ]
    client = Client()
    client.force_login(raj)
    for event in events:
        event.add_organizer(sam)
        page = client.get(f'/events/{event.pk}/edit/')
        print(f'Raj edits {event.title:10}:',
              page.status_code)
    rows = AuditEvent.objects.filter(actor=raj)
    for row in rows.order_by('id'):
        title = Event.objects.get(pk=row.target_id).title
        print('recorded:', row.action, row.outcome, title)
    transaction.set_rollback(True)
Raj edits Sam draft : 404
Raj edits Sam meetup: 403
recorded: edit_event refused Sam draft
recorded: edit_event refused Sam meetup

The 404 hides the draft’s existence; the 403 hides nothing, because the meetup’s page is public. Both checks happen in event_to_manage(), the one place every event action passes through.

What We Learned

  • Authentication proves who someone is; authorization decides what they may do, and most security mistakes are authorization mistakes.
  • is_staff and is_superuser are Django’s flags, not Otahque’s roles; a staff account may organize nothing, and an organizer needs no admin.
  • Model permissions name actions on a model; Meta.permissions adds custom ones; groups collect permissions into roles given in one step.
  • Groups belong in a data migration, which must create the permission rows first on a new database.
  • Django caches a user’s permissions on the object; fetch the user again after changing groups.
  • A permission is never about one record; Otahque’s rule follows the organizer assignment, in one model method every view calls.
  • has_perm() lets every active superuser through before any backend is asked, which is why the rule is not behind it.
  • IDOR is a page that trusts the number in its address; a shared check, scoped lookups, and a test for every row of the matrix prevent it.
  • The rule for organizer access lives in the models, so the admin and the Organizer access page refuse the same cases, including removing the last organizer.
  • An administrator who may change users must not be able to change their own permissions or join Administrators.
  • An audit record says who did what to which record, and whether it was allowed; it shares the action’s transaction and is kept apart from logs.

Key terms

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

Table 30.4 — Key terms from Chapter 30
Term Meaning
Authorization Deciding whether a person may do an action.
Model permission A named right on a model, such as events.change_event.
Custom permission A permission declared in a model's Meta.permissions.
Group A named set of permissions; its members hold them all.
Role What a kind of person may do; in Otahque, a group and its rules.
Object rule A rule about one record, such as "organizes this event".
Permission matrix A table of each person and action with the expected answer.
IDOR A page that finds a record by its number without checking access.
Privilege escalation Gaining rights beyond one's role, such as granting oneself permissions.
Re-authentication Asking for the password again before a sensitive change.
Audit record A row saying who did what to which record, and the outcome.
Data migration A migration that changes rows rather than tables.

Readiness checkpoint: you are ready for Chapter 31 when all 288 tests pass, makemigrations --check --dry-run prints No changes detected, the Organizers and Administrators groups exist, Soni can create an event and is refused someone else’s draft with “not found”, the Organizer access page opens only for the administrator and asks for the password before a change, the last organizer of an event cannot be removed, the administrator cannot add anyone to Administrators, refused attempts appear in Audit events, and the commit is made.

Git Commit

Your Chapter 30 work was committed in Step 12, with the message “Add roles, organizer access, and an audit trail”. It holds the audit app and its migration, the manage_organizers permission and its migration, the groups migration, the shared organizer rules and the active-account check in events/models.py, the safer organizer and user pages in the admin, the widget filter that gives the admin back its own classes, the Organizer access views, forms, templates, and menu link, the recording in each event view, the design note, ADR-004, the admin and event-state notes, three of Chapter 23’s tests changed in place, and thirty-one new tests.

PAGE 005

Test Your Knowledge: Interview Questions

These five questions rehearse the chapter at interview level, from junior to lead. L1 to L3 check what you have just done. L4 and L5 look ahead: attempt them now, and return after Chapters 50 and 67. They are extension questions, not a gate to the next chapter. L5’s code proof is the chapter’s optional lab.

L1 (Junior): What is the difference between authentication and authorization?

What the interviewer is testing: Can you separate the two, and give an example where one passes and the other fails?

Flip to check your answerFold answer back

Perfect answer: Authentication checks who someone is: a password, a code, a second factor. Authorization checks what that person may do. A member who signs in is authenticated, and may still not create an event, because creating needs a permission they do not hold. In Django, user.is_authenticated answers the first and user.has_perm() and the application’s own rules answer the second. Staff status is neither a role nor a right in Otahque: it only opens the admin.

Behind the scenes:

visitor     -> not signed in: sent to sign in
member      -> signed in, no add_event: 403
staff only  -> signed in, staff, no add_event: 403

Code proof: l1_who.py:

visitor     signed in: False  may create: False
member      signed in: True   may create: False
staff only  signed in: True   may create: False

Common mistakes:

  • Treating “signed in” as “allowed”.
  • Using is_staff as an application role.
  • Checking authorization only by hiding buttons in templates.

Follow-up the interviewer might ask:

  • “Where does a 401 fit beside 403 and a redirect to sign in?”
  • “How would you test that every page checks authorization?”

L2 (Mid-Level): Raj requests the edit page of Sam’s draft. Predict the response.

What the interviewer is testing: Can you trace a request through a shared check and choose between 404 and 403?

Flip to check your answerFold answer back
Five numbered steps. Raj, an organizer, opens the edit page of Sam’s draft. event_to_manage() finds the draft by its number. is_visible_to(Raj): a draft he does not organize. 404, the same as a number that does not exist. A refused AuditEvent names Raj and the draft.
Figure 30.5 — Raj asks for Sam’s draft.

Perfect answer: 404. The edit view calls event_to_manage(), which finds the event and asks is_visible_to(Raj). A draft is visible only to its organizers and holders of view_event; Raj is neither, so the answer is the same 404 as for a number with no event, and the draft’s existence stays hidden. For Sam’s published event the answer would be 403, because anyone may see it. Either way, a refused edit_event record names Raj.

Behind the scenes:

draft, not his       -> 404, recorded
published, not his   -> 403, recorded
number with no event -> 404, not recorded

Code proof: the Mini-Challenge’s l2_predict.py:

Raj edits Sam draft : 404
Raj edits Sam meetup: 403
recorded: edit_event refused Sam draft
recorded: edit_event refused Sam meetup

Common mistakes:

  • Answering 403 for a hidden draft, which confirms that it exists.
  • Checking only in the template, so the URL still works.
  • A new view that looks the event up itself instead of through the shared check.

Follow-up the interviewer might ask:

  • “Would random identifiers instead of numbers fix IDOR?”
  • “What should an API return for the same request?”

L3 (Senior): Why does editing need both the Organizers group and an assignment?

What the interviewer is testing: Can you defend a two-part rule with evidence, and say what each part protects?

Flip to check your answerFold answer back
Five numbered steps. Goal: organizers manage only their own events. The group answers: may this person organize? The assignment answers: this event? The matrix test has a row for each kind of person. Staff, superuser, administrator: refused on the pages.
Figure 30.6 — Two conditions, each with a job.

Perfect answer: They answer different questions. The group says whether someone may organize at all; the administrator grants it once, and removing it ends every organizer right at once. The assignment says which events, PR-4’s “organizers manage only assigned events”. Either alone is wrong: the group alone would let every organizer edit every event, and the assignment alone would let an assignment outlive a revoked role. The matrix test proves each row, including the people who must be refused: staff, superusers, and administrators manage no event on Otahque’s pages.

Behind the scenes:

group, no assignment   -> cannot edit
assignment, no group   -> cannot edit
group and assignment   -> can edit

Code proof: l3_two.py:

from datetime import timedelta

from django.contrib.auth.models import Group
from django.db import transaction
from django.utils import timezone

from accounts.models import User
from events.models import Event


def fresh(user):
    """Fetch the user again, without cached permissions."""
    return User.objects.get(pk=user.pk)


with transaction.atomic():
    organizers = Group.objects.get(name='Organizers')
    soni = User.objects.create_user(
        'soni.demo@example.org', display_name='Soni demo')
    start = timezone.now() + timedelta(days=7)
    swap = Event.objects.create(
        title='Book swap', starts_at=start,
        ends_at=start + timedelta(hours=2),
        timezone='UTC', location='Delhi', capacity=20)
    soni.groups.add(organizers)
    print('group only:     ',
          swap.can_be_edited_by(fresh(soni)))
    swap.add_organizer(soni)
    soni.groups.remove(organizers)
    print('assignment only:',
          swap.can_be_edited_by(fresh(soni)))
    soni.groups.add(organizers)
    print('both:           ',
          swap.can_be_edited_by(fresh(soni)))
    transaction.set_rollback(True)
group only:      False
assignment only: False
both:            True

Common mistakes:

  • One “is organizer” flag on the user, which cannot say which event.
  • Letting staff or superusers bypass the rule on the site “for convenience”.
  • Testing only the allowed row, never the refusals.

Follow-up the interviewer might ask:

  • “How would co-organizer invitations change this, and PR-6?”
  • “Where would a community’s own organizers fit (Chapter 67)?”

L4 (Staff): A test adds Soni to Organizers and still gets 403. Diagnose it.

What the interviewer is testing: Can you reason from how Django evaluates permissions to a fix, without weakening the rule?

Flip to check your answerFold answer back
Five numbered steps. A test adds Soni to Organizers, then gets 403. Same user object? Its permissions were cached. refresh_from_db() does not clear the cache. Fetch the user again, or sign in again in the test. PermissionCacheTests shows both answers.
Figure 30.7 — A group added, and still refused.

Perfect answer: Django caches a user’s permissions on the user object the first time has_perm() runs, and refresh_from_db() does not clear that cache. If the test asked before adding the group, or the code under test kept the same object, the old answer stays. Fetching the user again gives the new one, and so does a request through the test client, which loads the user afresh. The fix is in the test, not the rule. If the 403 survives a fresh user, check the second condition: is there a current assignment? And is the account active, since has_organizer() now requires it?

Behind the scenes:

same object         -> False
refresh_from_db()   -> False
fetched again       -> True

Code proof: l4_cache.py:

from django.contrib.auth.models import Group
from django.db import transaction

from accounts.models import User

ADD = 'events.add_event'
with transaction.atomic():
    soni = User.objects.create_user(
        'soni.demo@example.org', display_name='Soni demo')
    print('before the group:     ', soni.has_perm(ADD))
    soni.groups.add(Group.objects.get(name='Organizers'))
    print('same object:          ', soni.has_perm(ADD))
    soni.refresh_from_db()
    print('after refresh_from_db:', soni.has_perm(ADD))
    soni = User.objects.get(pk=soni.pk)
    print('fetched again:        ', soni.has_perm(ADD))
    transaction.set_rollback(True)
before the group:      False
same object:           False
after refresh_from_db: False
fetched again:         True

Common mistakes:

  • Loosening the rule until the test passes.
  • Clearing private cache attributes instead of fetching the user.
  • Forgetting the assignment, the second half of the rule.

Follow-up the interviewer might ask:

  • “Could the cache ever affect a real request?”
  • “How would you make this failure message clearer?”

L5 (Lead): Should Otahque use django-rules, django-guardian, or its own model methods?

What the interviewer is testing: Can you compare designs by how they fail, and name when you would change your mind?

Flip to check your answerFold answer back
Five numbered steps. Goal: one rule, every page, no surprises. has_perm(perm, obj) lets every active superuser through. Per-object rows would repeat OrganizerAssignment. Model methods, groups, and a matrix test. Revisit for the API (50) and communities (67).
Figure 30.8 — Choosing where the rule lives.

Perfect answer: Model methods, for now, as ADR-004 records. django-rules puts predicates behind has_perm(perm, obj), which reads well, but has_perm() lets every active superuser through before any backend is asked, so every superuser could manage every event on the site. django-guardian stores a permission row per member and object, which would repeat what OrganizerAssignment already holds, and two sources of truth drift apart. Model methods keep the rule beside the data, the same for everyone, with one test per matrix row. I would revisit when the API (Chapter 50) needs the rules in a shared module, or when communities (Chapter 67) bring per-community roles, where a package or a fuller role model may earn its place.

Behind the scenes:

ModelBackend, organizer       -> False: objects ignored
any backend, superuser        -> True: asked before backends
can_be_edited_by(superuser)   -> False: the same rule as all

Code proof: the optional lab. l5_backend.py writes the smallest object backend, answering events.change_event through can_be_edited_by(), and puts it in place only while the file runs, so your settings are untouched:

from datetime import timedelta
from unittest import mock

from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import Group
from django.db import transaction
from django.utils import timezone

from accounts.models import User
from events.models import Event

CHANGE = 'events.change_event'


class OrganizerBackend:
    """Lab only: answers change_event for one event."""

    def has_perm(self, user, perm, obj=None):
        if perm != CHANGE or obj is None:
            return False
        return obj.can_be_edited_by(user)


with transaction.atomic():
    sam = User.objects.create_user(
        'sam.demo@example.org', display_name='Sam demo')
    sam.groups.add(Group.objects.get(name='Organizers'))
    root = User.objects.create_superuser(
        'root.demo@example.org', display_name='Root demo')
    start = timezone.now() + timedelta(days=7)
    draft = Event.objects.create(
        title='Sam demo draft', starts_at=start,
        ends_at=start + timedelta(hours=2),
        timezone='UTC', location='Leeds', capacity=20)
    draft.add_organizer(sam)
    sam = User.objects.get(pk=sam.pk)
    print('ModelBackend only')
    print('  organizer Sam:', sam.has_perm(CHANGE, draft))
    print('  superuser:    ', root.has_perm(CHANGE, draft))
    backends = [ModelBackend(), OrganizerBackend()]
    with mock.patch('django.contrib.auth.get_backends',
                    return_value=backends):
        print('With the lab backend')
        print('  organizer Sam:',
              sam.has_perm(CHANGE, draft))
        print('  superuser:    ',
              root.has_perm(CHANGE, draft))
    print('can_be_edited_by(superuser):',
          draft.can_be_edited_by(root))
    transaction.set_rollback(True)
ModelBackend only
  organizer Sam: False
  superuser:     True
With the lab backend
  organizer Sam: True
  superuser:     True
can_be_edited_by(superuser): False

With the backend, the organizer is finally allowed through has_perm(), and the superuser is allowed whatever the backend says. That is the reason Otahque does not route its rule this way.

Common mistakes:

  • Adding a package before writing down the rules it must enforce.
  • Keeping the same rule in two places, such as a package and model methods.
  • Choosing role-based access for decisions that depend on one record.

Follow-up the interviewer might ask:

  • “What would make you move the rules into their own module?”
  • “How would you migrate if Otahque later adopted django-rules?”
PAGE 006