ContentsClose contents
Pre-release
Chapter 23 · Django admin fundamentals: the administrator’s tool for Otahque’s dataCHAPTER 23

Complete six-part pre-release for review. Organizers do not use the admin site; their own pages arrive in Chapter 26. No migration is added.

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 TWENTY-THREE

Django admin fundamentals: the administrator’s tool for Otahque’s data

Stage 3: Data and the database (Chapters 15 to 23)

Prerequisites: Chapters 15 to 22, including the Chapter 22 project, its 58 passing tests, its four events, three members, their registrations, Sam’s organizer assignment, and the superuser account you created for Sam in Chapter 18

What you’ll build: An admin site for the community administrator, at an address read from the environment, with an event list that shows drafts, each start in UTC and in the event’s own zone, and the places left; registrations shown as read-only history; organizer assignments that can be granted and revoked but never deleted; a user page that never shows a password; a read-only audit log of every change made through the admin; and nineteen tests that prove who may do what.

Why This Matters

Since Chapter 18, Otahque’s data has lived in four tables, and the only window into them is the Django shell. That suits you, the developer, but not the person who runs the community. The administrator needs a page in the browser to check rows and to make the corrections a real community needs: a location that changed, a capacity typed wrongly, and, from Chapter 2’s requirement PR-6, granting a member organizer access to an event and revoking it again. Django ships such a page, the admin site. Your project has routed it at /admin/ since Chapter 6, and it is still empty.

The admin site is powerful, and its default power is the problem. Out of the box, an account with every permission can delete a registration that Chapter 20 protected as history, edit a registration and skip the registration rules that Chapters 31 and 33 will build, and type an event’s times without knowing which time zone they are read in. Chapter 17 warned that Django’s staff flag is not an Otahque role. So this chapter does not simply switch the admin on. It configures it as one person’s tool, with limits chosen on purpose, and it proves each limit with a test.

Who uses it is a decision, and it was made before this chapter: the admin site is the administrator’s tool. Organizers manage their own events on Otahque’s own pages from Chapter 26, and visitors and members never see the admin. On your computer you sign in as Sam, because Sam’s account is the superuser you created in Chapter 18. That is a convenience for development, not Sam’s role in the product, where he is an organizer.

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

  • register a model with the admin site and choose its list columns, filters, search, and order;
  • decide for each model what the admin may view, add, change, and delete, and prove every refusal with a test;
  • show an event’s start in UTC and in its own time zone, and explain why times typed in the admin are read as UTC;
  • keep history read-only, and make sure Chapter 21’s rules still reach the page when a form leaves fields out;
  • keep the admin’s pages at a fixed number of queries with joins and query-count tests;
  • read the admin’s audit log, and say what it records and what it does not.

Forms you write yourself are Chapter 24, organizer pages Chapter 26, sign-up and sign-in for members Chapters 27 and 28, the design of groups and permissions Chapter 30, and the registration workflow Chapters 31 and 33. Hardening the admin, including two-factor sign-in for staff, is planned for Chapters 29, 59, 60, and 63.

PAGE 001

What You Need to Know

What the admin site is, and who it is for

New Tool: the Django admin site

What problem exists? People who look after an application need to read and correct its data, and the application’s own pages show only what visitors and members need.

What did people do before? They typed queries into a database client, or wrote a private page for every table, each with its own list, form, checks, and permissions.

What is it? The admin site is an application that ships with Django, django.contrib.admin. For every model you register with it, it builds a list page, an add page, a change page, a delete page, and a history page, from the model’s fields. It signs people in, checks Django’s permissions, validates with the model’s own rules, and records each change it makes.

Why use it? One configuration class per model gives the administrator a complete, consistent tool, so you spend your effort on the limits rather than on the pages.

Now let’s use it. Step 2 signs in, Steps 4 to 7 register Otahque’s models, and Step 8 writes down where the admin’s job ends.

Django’s documentation is direct about the admin’s purpose: it is an organization’s internal management tool, not the place to build a site’s own pages. That matches Otahque’s plan, and Figure 23.1 shows it. Four kinds of people use Otahque. Visitors read published events. Members have accounts, and from Chapter 31 they register for events and cancel their places. Organizers are members who run particular events, and Chapter 26 gives them pages for those events. The administrator looks after the whole community, and is the only one who uses the admin site.

Two zones above one green database card, with an arrow from each zone to it. The left zone, Otahque’s own pages, holds three blue cards: Visitors read published events; Members register and cancel their own places, in Chapter 31; Organizers manage their own events, in Chapter 26, through an organizer assignment. The right zone, The admin site at DJANGO_ADMIN_URL, holds a blue card, The administrator, who checks rows and makes permitted corrections, and two purple cards: is_staff lets an account sign in here and nothing more, and Permissions decide what each admin page lets that account see and change. The database card reads: events, registrations, assignments, users.
Figure 23.1 — Visitors, members, and organizers use Otahque’s pages; only the administrator uses the admin site.

Three flags on Chapter 17’s user model decide what an account can do in the admin. is_active must be true for the account to sign in at all. is_staff lets an active account sign in to the admin site, and does nothing else: a staff account with no permissions sees an empty page. is_superuser grants every Django permission without listing any. Being an organizer is none of these. It is a row in Chapter 20’s OrganizerAssignment table, which says which member organizes which event, and only Otahque’s own pages will read it. Chapter 18 said a superuser can change everything in the admin site. That is Django’s default, and this chapter narrows it: some refusals in this chapter apply to every account, superusers included, because they are product rules, such as “registrations are history”, and not questions of trust.

Registering a model: ModelAdmin

Until a model is registered, the admin site does not know it exists. Registration pairs a model with a class that describes its pages.

New Concept: ModelAdmin

What problem exists? A generated page needs to know which columns to list, what to search, which fields may be edited, and what is refused.

What did people do before? They wrote each list and form by hand, as The Custom Way below does.

What is it? A ModelAdmin is a class, a subclass of admin.ModelAdmin, whose attributes describe the pages for one model. The decorator @admin.register(Event) registers the model with the class that follows it. Attributes such as list_display choose the list’s columns; methods such as has_delete_permission() answer questions the admin asks while it builds each page.

Why use it? The pages stay Django’s, so they keep working as Django changes, while every Otahque decision lives in one short class beside the app that owns the model.

Now let’s use it. Step 4 writes EventAdmin, and Steps 5 to 7 write one class for each of the other models.

Table 23.1 lists the options this chapter uses. Each is introduced again where a step first needs it.

Table 23.1 — ModelAdmin options used in this chapter
Option What it controls
list_display The columns of the list page: fields, or methods marked with @admin.display
list_filter The filters beside the list, such as status
search_fields The fields the search box looks in
ordering The list's order, such as newest first
fields, readonly_fields Which fields the change page shows, and which it shows without an input
list_select_related Related rows joined into the list's query
inlines Related rows shown on a parent's page, such as an event's registrations
actions The bulk actions offered above the list
has_add_permission() and its siblings Whether a page or button is offered, and whether a request is refused
get_queryset() The rows the admin starts from, such as events with their places left

admin.py in each app is where these classes go. When the project starts, the admin site calls autodiscover(), which imports the admin.py module of every installed app, so a class registered there is found without being imported anywhere else. Your three admin.py files are still the stubs startapp wrote, which is why the admin is empty.

Who may do what: permissions

When Chapter 18 ran migrate, Django created four model permissions for every model, stored in the auth_permission table: add_event, change_event, delete_event, and view_event for events, and the same four for each other model. An account holds a permission directly, or through a group, a named set of permissions. The admin offers a page or a button only when the account holds the matching permission: no delete_registration, no delete button.

A ModelAdmin can narrow that further. has_add_permission(), has_change_permission(), has_delete_permission(), and has_view_permission() are methods the admin calls with each request. By default they check the account’s model permissions; a method that returns False refuses the action for everyone, superusers included. This chapter uses that to state Otahque’s rules once, in code, as Figure 23.2 shows.

A grid. Columns: View, Add, Change, Delete. Rows: Events: yes, yes, yes, and Only without history, in grey. Registrations: yes, then no, no, no, in red. Organizer assignments: yes, yes, Revoke only in grey, no. Users: yes, no, Yes, never the password in grey, and No: deactivate instead in grey. Log entries: yes, then no, no, no. Green cells with a tick mean allowed; red cells with a cross mean refused.
Figure 23.2 — What the admin allows for each model, for every account in this chapter, superusers included.

Under the Hood: how the admin decides what to show

Every admin page starts with AdminSite.has_permission(), which requires an active account with is_staff; anyone else is sent to the admin’s sign-in page. The index page then asks each registered ModelAdmin for get_model_perms(), a dictionary of the four permission methods’ answers, and lists only models where at least one is true, with an Add link only when adding is allowed. A list page needs view or change permission; when change is refused but view is allowed, the change page becomes a read-only “View” page with no Save button. Bulk actions are filtered the same way: the built-in “Delete selected” action carries allowed_permissions = ('delete',), so it disappears wherever has_delete_permission() says no. A refused request, such as a forged form sent to a read-only page, gets status 403, “Forbidden”, so the rule holds even when the button is not there to press.

Chapter 30 designs Otahque’s groups and permissions. This chapter assigns none: Sam holds them all as a superuser, and the tests in Step 3 create accounts with one permission or none to prove what each sees.

Times in the admin

Chapter 16 stored every event’s start and end as an instant in UTC, with the event’s own zone, such as Asia/Kolkata, in a separate field. Pages show those instants in the event’s zone. The admin does not know that convention. When someone types a date and time into the admin’s form, Django reads it in the current time zone, which is TIME_ZONE in settings, UTC, unless code activates another. So 15:00 typed for the Django workshop in Kolkata is stored as 15:00 UTC, which is 20:30 in Kolkata, five and a half hours later than the organizer meant.

Otahque’s answer in this chapter is to make the mismatch impossible to miss rather than to hide it: the form says “In UTC, not the event’s own time zone” beside each time field, the list shows the start in UTC and again as a “Local start” in the event’s zone, and the change page shows the local start too. If the browser’s zone differs from the server’s, the admin also adds its own note, such as “Note: Enter times in the UTC timezone. (You are 5.5 hours ahead.)”: that note is about your computer’s zone, not the event’s. Each person’s own time zone arrives later: Chapter 27 adds it to a profile, and Chapter 28 activates it for each request, so that pages show times in the viewer’s zone as well as the venue’s.

Forms the admin builds, and the rules they check

The admin’s add and change pages are forms. Django builds each one from the model, as a ModelForm, a form generated from a model’s fields; Chapter 24 writes ModelForms of its own. When someone saves, the form calls the model’s full_clean(), which Chapter 21 wrote rules for: field validators, such as validate_timezone_name(), the model’s clean(), and its constraints, such as “capacity must be more than 0”. So Chapter 21’s messages reach a person for the first time here, beside the field or at the top of the form, and nothing is saved until they pass, as Figure 23.3 shows.

Three numbered cards in a row joined by arrows: 1, a blue Event page card, the browser sends the form; 2, a purple ModelForm card, built by the admin from the model; 3, a purple full_clean() card, fields, clean(), and constraints whose fields are on the form. Below the third card, an orange validate_constraints() card points up into it: our override checks every rule for organizer assignments. From the full_clean() card, arrows lead down to two cards numbered 4: a red card, A rule fails, Chapter 21’s message on the page, nothing saved; and a green card, Every rule holds, the row is saved and a log entry records who changed what.
Figure 23.3 — One save in the admin: the form checks the model’s rules before anything is written.

There is one gap, and Step 5 meets it. A form checks only the fields it holds. A field the page shows read-only, or leaves out, is not on the form, and full_clean() then skips any constraint that names that field, because it cannot be sure the value it would check is the one that will be saved. The database still refuses a row that breaks the constraint, but the person sees an error page instead of a message. Step 5 shows the failure, and fixes it for the one model that needs it.

The admin’s change history

Chapter 18’s migrations created a table called django_admin_log. Its model is LogEntry, in django.contrib.admin.models. Every add, change, and delete made through the admin writes one row: who did it, when, which object, as its text at that moment, and, for a change, which fields changed, such as “Changed Location.”. Each object’s page has a History button that lists its rows. Django does not register LogEntry with the admin, so there is no page listing them all; Step 7 adds one, read-only, and calls it Otahque’s audit log.

Two zones above a dashed orange card. The left zone, Written to the log, holds three green cards with ticks: Add, a new row, by whom and when; Change, which fields changed, such as Changed Location; Delete, the deleted row, by its name. The right zone, Not written, holds three grey cards with crosses: Shell and scripts, save(), update(), and migrations; Otahque’s own pages, registering, cancelling, organizing; Signing in, successful and refused sign-ins. The dashed card below reads: A business audit trail, every important action, from any page, Chapters 30 and 65.
Figure 23.4 — The admin’s log records what was done through the admin, and nothing else.

The log is useful and narrow. It records only what passes through the admin’s pages: changes made in the shell, by scripts, by migrations, or by Otahque’s own pages are not in it, and nor are sign-ins. Its rows are ordinary rows, so anyone who can write to the database can change them. A business audit trail, recording important actions from every part of Otahque, is planned for Chapters 30 and 65.

Try it yourself

Que. 1 A member, Raj, has an account with is_active true and is_staff false, and he opens /admin/. What does he see, and what would change if an administrator ticked is_staff and gave him nothing else?

Flip to check your answerFold answer back

Answer. He is sent to the admin’s sign-in page, and his own email and password are refused there with a message asking for a staff account. With is_staff ticked and no permissions, he could sign in, and the index would say he has no permission to view or edit anything. He would still not organize any event: that needs an organizer assignment.

Prefer the admin site, your own pages, or the shell?

Use the admin site for the administrator’s checks and occasional corrections to individual rows, by one trusted person, with the limits this chapter sets. Write Otahque’s own pages for anything that ordinary users do, or that follows a workflow with rules of its own, such as registering, cancelling, or organizing an event: those pages check who owns what, which the admin’s permissions cannot (the L5 interview question explains why). Use the shell, or a management command written with tests, for changes to many rows at once, and remember that the admin’s log does not see them.

Two more cautions go with that choice. The admin site is a high-value target, because it can change every table: Step 2 moves its address out of the code, and the planned hardening adds two-factor sign-in and more. And because the admin edits rows directly, every rule that matters must already be in the model, as Chapter 21’s are, or it does not apply in the admin.

In practice: a room change the night before

Situation. The library moves the Python meetup to a different room the evening before it starts, and the organizer cannot reach a computer.

Application. The administrator opens the event in the admin site, corrects the location, and saves. Chapter 21’s rules check the change, the public page shows the new room at once, and the audit log records who changed the location and when.

Consideration. The log shows that the location changed, not why, and nobody who had already read the page is told. Telling registered members about changes is a separate feature, planned with Otahque’s emails in later chapters; the admin site is not a messaging tool.

PAGE 002

How We Build It

Start from Chapter 22, in the folder containing manage.py, with your own .env, the locked environment, 58 passing tests, every migration applied, and the rows Chapter 22 left: four events, two of them published; Sam, Sai, and Raj; Sai’s two active registrations and Raj’s cancelled one; Sam’s organizer assignment for the Python meetup; and Sam’s superuser password, which you chose in Chapter 18. Step 2 signs in and moves the admin’s address into settings, in config/settings.py, config/urls.py, .env.example, and your .env. Step 3 writes the access tests in config/tests.py. Steps 4 to 7 each write a model’s tests first and then its admin class: events and the registrations shown under them in events/admin.py, registrations in registrations/admin.py, organizer assignments back in events/admin.py with one method added to events/models.py, users in accounts/admin.py, and the audit log in the same file. Step 8 writes docs/design/admin.md, and Step 9 commits. At the end, 77 tests pass, the admin site lists Otahque’s four models and the audit log with the limits of Figure 23.2, and there is no new migration.

The Custom Way

Without the admin site, every correction page is written by hand. This illustration is a tiny editing function for events held in a dictionary, with the checks a real page would need: who may edit, one of Chapter 21’s rules, and a record of the change. Run it with any Python, and do not add it to the project:

FIELDS = ['title', 'capacity']
rows = {1: {'title': 'Python meetup', 'capacity': 40}}
log = []


def edit(user, row_id, changes):
    if not user['is_staff']:
        return 'refused'
    if int(changes.get('capacity', 1)) <= 0:
        return ['Capacity must be more than 0.']
    before = dict(rows[row_id])
    rows[row_id].update(changes)
    changed = [name for name in FIELDS
               if before[name] != rows[row_id][name]]
    log.append((user['email'], row_id, changed))
    return 'saved'


sam = {'email': 'sam@example.org', 'is_staff': True}
print(edit(sam, 1, {'capacity': 0}))
print(edit(sam, 1, {'capacity': 45}))
print(log)
['Capacity must be more than 0.']
saved
[('sam@example.org', 1, ['capacity'])]

It works for one model with two fields. Now count what is missing. There is no page: no list, no form, no search, and no way to sign in. The capacity rule is copied from the model, so the two copies can drift apart. The permission check is one flag, written by hand, and every other model needs its own function with its own checks and its own log. The admin site does all of this from the model: it builds the pages, signs people in, asks the model for its rules, checks permissions per model, and writes the log. What it cannot know is Otahque’s decisions, such as “registrations are history”, and those are what this chapter writes.

The Django Way

Nine steps follow. Step 1 checks the start, Step 2 signs in and moves the address, Step 3 writes the access tests, Steps 4 to 7 register the models and the audit log, each with its tests first, Step 8 records the boundary, and Step 9 commits.

Step 1: Check the starting point

Run every test, beside manage.py, in PowerShell, Git Bash, a macOS shell, or Linux/WSL Bash:

uv run python manage.py test

Expected result, shortened with ...:

Found 58 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
..........................................................
...
Ran 58 tests in ...

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

Then look for the admin in the files that matter. git grep searches the files Git tracks, and the quoted pattern "*/admin.py" means every app’s admin.py, in every shell:

git grep -n admin -- config/urls.py "*/admin.py"
accounts/admin.py:1:from django.contrib import admin
config/urls.py:2:from django.contrib import admin
config/urls.py:6:    path('admin/', admin.site.urls),
events/admin.py:1:from django.contrib import admin
registrations/admin.py:1:from django.contrib import admin

config/urls.py already sends every address that starts with admin/ to admin.site.urls, the admin site’s own URL patterns; startproject wrote that line in Chapter 6. Each admin.py imports the admin and registers nothing.

Step 2: Sign in, and move the admin’s address

Start the development server, in any of the four shells, and leave it running:

uv run python manage.py runserver

Open http://127.0.0.1:8000/admin/. The admin sends you to its sign-in page, /admin/login/?next=/admin/, which asks for an “Email address”, because Chapter 17 made the email the field people sign in with. Sign in with sam@example.org and the password you chose for Sam in Chapter 18. The page that opens is the admin’s index, headed “Django administration” and “Site administration”, and it lists one model: Groups, under “Authentication and Authorization”. Django’s auth app registers Groups itself. Otahque’s models are missing, and so are its users: Django registers its own user admin only for its own User model, and Chapter 17 replaced that model with Otahque’s.

Before registering anything, give the admin site an address of your choosing. Every Django project starts with the admin at /admin/, so automated scripts that probe websites try that address first. An address that is hard to guess does not make the admin secure, but it keeps those scripts away, and the address is a setting that differs between your computer and each deployment, which is what Chapter 8’s .env file is for. Stop the server with Ctrl+C. Open config/settings.py and add these lines after the ALLOWED_HOSTS setting:

# The admin site's path: admin/ locally, and a path that is
# hard to guess in each deployment. It ends with /.
ADMIN_URL = config('DJANGO_ADMIN_URL', default='admin/')
if ADMIN_URL.startswith('/') or not ADMIN_URL.endswith('/'):
    raise ImproperlyConfigured(
        'DJANGO_ADMIN_URL must end with / and not start '
        'with it; see .env.example.'
    )

config() reads DJANGO_ADMIN_URL from the environment or from .env, and uses admin/ when it is missing. The check refuses a value that would build a broken pattern: Django’s URL patterns never start with /, and this one must end with / so that the admin’s own pages, such as admin/login/, follow it. Then open .env.example and add three lines at the end, so the next developer knows the setting exists:

# The admin site's path, ending with /. Keep admin/ locally;
# choose a path that is hard to guess for each deployment.
DJANGO_ADMIN_URL=admin/

Add the same setting to your own .env, at the end, keeping admin/ on your computer:

DJANGO_ADMIN_URL=admin/

On a deployed Otahque, the value is a path of its own, such as manage-7Kq2/, chosen once and kept out of the code like the secret key. Now replace config/urls.py with:

"""URL configuration for the Otahque project."""
from django.conf import settings
from django.contrib import admin
from django.urls import include, path

admin.site.site_header = 'Otahque administration'
admin.site.site_title = 'Otahque admin'

urlpatterns = [
    path(settings.ADMIN_URL, admin.site.urls),
    path('', include('events.urls')),
]

The pattern now comes from the setting. The two admin.site lines replace Django’s default title, “Django administration”, with Otahque’s own in the header and in the browser tab. Check the project:

uv run python manage.py check
System check identified no issues (0 silenced).

Common Error: the address has no final slash

With DJANGO_ADMIN_URL=admin in .env, every command stops with django.core.exceptions.ImproperlyConfigured: DJANGO_ADMIN_URL must end with / and not start with it; see .env.example. That is the check you just wrote, refusing a value that would make the admin’s pages unreachable. Add the final /. A value set in your shell’s environment wins over .env, so if .env looks right, check the environment too.

Start the server again and reload the admin. The header now reads “Otahque administration”, and the page is unchanged otherwise. Leave the server running while you work, and stop and start it if a page looks stale; the tests below do not need it.

Step 3: Write the access tests first

The first tests decide who may enter, before any model is registered. They live in config/tests.py, beside Chapter 18’s migration test, because they are about the whole admin site rather than one app. They need the address of admin pages, and Django names those addresses in one pattern: admin: followed by the app’s label, the model’s name in lower case, and the page, such as admin:events_event_changelist for the event list and admin:events_event_change for one event’s page. Add a helper to events/tests.py, after save_event(), separated from it and from the next function by two blank lines, so every test file can build those names the same way:

def admin_url(model, page, *args):
    """Return an admin page's address, such as an event's."""
    meta = model._meta
    name = f'admin:{meta.app_label}_{meta.model_name}_{page}'
    return reverse(name, args=args)

model._meta is the model’s description, which Django fills in from the class; app_label is events and model_name is event. Then open config/tests.py and replace its imports, the four lines from from io import StringIO to from django.test import TestCase, with:

from io import StringIO

from django.contrib.auth.models import Permission
from django.core.management import call_command
from django.test import TestCase
from django.urls import reverse

from accounts.models import User
from events.models import Event
from events.tests import admin_url, save_event

PASSWORD = 'correct horse battery'
REFUSED = (
    'Please enter the correct email address and password '
    'for a staff account.'
)

MigrationTests stays as it is. Add a class at the end of the file:

class AdminAccessTests(TestCase):
    """Who may enter the admin, and what staff may do."""

    @classmethod
    def setUpTestData(cls):
        cls.event = save_event()

    def sign_in(self, email, **flags):
        """Create a member and sign in through the admin."""
        User.objects.create_user(
            email, PASSWORD, display_name='Test', **flags
        )
        return self.client.post(
            reverse('admin:login'),
            {'username': email, 'password': PASSWORD},
        )

    def staff(self):
        """Create a staff member with no permissions."""
        return User.objects.create_user(
            'helper@example.org', display_name='Helper',
            is_staff=True,
        )

    def test_visitor_is_sent_to_sign_in(self):
        index = reverse('admin:index')
        self.assertRedirects(
            self.client.get(index),
            f"{reverse('admin:login')}?next={index}",
        )

    def test_member_is_refused(self):
        response = self.sign_in('raj@example.org')
        self.assertContains(response, REFUSED)

    def test_inactive_staff_is_refused(self):
        response = self.sign_in(
            'old@example.org', is_staff=True,
            is_active=False,
        )
        self.assertContains(response, REFUSED)

    def test_staff_flag_alone_grants_nothing(self):
        helper = self.staff()
        self.client.force_login(helper)
        response = self.client.get(reverse('admin:index'))
        self.assertContains(
            response, 'permission to view or edit anything'
        )
        response = self.client.get(
            admin_url(Event, 'changelist')
        )
        self.assertEqual(response.status_code, 403)
        self.assertFalse(
            helper.organizer_assignments.exists()
        )

    def test_view_permission_has_no_save(self):
        helper = self.staff()
        helper.user_permissions.add(
            Permission.objects.get(codename='view_event')
        )
        self.client.force_login(helper)
        url = admin_url(Event, 'change', self.event.pk)
        response = self.client.get(url)
        self.assertContains(response, 'Python meetup')
        self.assertNotContains(response, 'name="_save"')
        response = self.client.post(url, {'capacity': 1})
        self.assertEqual(response.status_code, 403)

Each test is one rule from Figure 23.1. A visitor is sent to sign in, with ?next= holding the page they asked for. A member and an inactive staff account both get the admin’s refusal: the first because is_staff is false, the second because Django refuses inactive accounts before it looks at anything else. sign_in() posts the email and password to the admin’s sign-in page, as a browser does. The last two tests use force_login(), which signs an account in without a password. A staff account with no permissions sees “You don’t have permission to view or edit anything.” on the index, is refused the event list with status 403, and organizes nothing: organizer_assignments is Chapter 20’s reverse relation, and it is empty. With only view_event, the event page opens with no Save button, and a forged save is refused. Permission.objects.get(codename='view_event') fetches one of the rows Chapter 18’s migrations created. Run the tests in config:

uv run python manage.py test config

Expected result, shortened with ...:

Found 6 test(s).
...
..EE..
...
ERROR: test_staff_flag_alone_grants_nothing (config.tests...
...
...NoReverseMatch: Reverse for 'events_event_changelist' ...
...
ERROR: test_view_permission_has_no_save (config.tests.Adm...
...
...NoReverseMatch: Reverse for 'events_event_change' not ...
...
FAILED (errors=2)
Destroying test database for alias 'default'...

Of the five new tests, three pass already, because they test Django’s own sign-in rules; the sixth test run is Chapter 18’s migration test. The two errors come from the tests that need event pages: until events are registered, the admin has no page named admin:events_event_changelist, so reverse() raises NoReverseMatch before any request is made. Step 4 registers events, and both pass.

The staff test is the one to remember. Chapter 17 kept the staff flag apart from the organizer role, and this test is the proof: an account can be staff and organize nothing, and an organizer, from Chapter 26, will organize without being staff. Groups, which the index shows, are where Chapter 30 will collect permissions for the administrator’s role; this chapter leaves the Groups list empty.

Step 4: Register events

Events come first, because the administrator corrects them most. The tests describe the list and the event page before they exist. Add a function and a class at the end of events/tests.py:

def event_form(event, **changes):
    """Build what the admin's event page sends; UTC times."""
    data = {
        'title': event.title,
        'status': event.status,
        'starts_at_0': f'{event.starts_at:%Y-%m-%d}',
        'starts_at_1': f'{event.starts_at:%H:%M}',
        'ends_at_0': f'{event.ends_at:%Y-%m-%d}',
        'ends_at_1': f'{event.ends_at:%H:%M}',
        'timezone': event.timezone,
        'location': event.location,
        'capacity': event.capacity,
        'registrations-TOTAL_FORMS': 0,
        'registrations-INITIAL_FORMS': 0,
    }
    data.update(changes)
    return data


class EventAdminTests(TestCase):
    """The event pages: list, UTC times, rules, history."""

    @classmethod
    def setUpTestData(cls):
        cls.sam = User.objects.create_superuser(
            'sam@example.org', display_name='Sam'
        )
        cls.workshop = save_event(
            title='Django workshop',
            starts_at=datetime(2026, 12, 3, 9, tzinfo=UTC),
            timezone='Asia/Kolkata',
            location='Virtual',
        )
        save_event(title='Spring planning',
                   status=Event.Status.DRAFT)
        sai = User.objects.create_user(
            'sai@example.org', display_name='Sai'
        )
        cls.place = Registration.objects.create(
            event=cls.workshop, member=sai
        )

    def setUp(self):
        self.client.force_login(self.sam)
        self.url = admin_url(Event, 'change',
                             self.workshop.pk)

    def test_list_shows_drafts_local_start_and_places(self):
        response = self.client.get(
            admin_url(Event, 'changelist')
        )
        self.assertContains(response, 'Spring planning')
        self.assertContains(
            response, 'Thu 03 Dec 2026, 14:30 IST'
        )
        self.assertContains(
            response, '<td class="field-places">39</td>',
            html=True,
        )
        self.assertNotContains(response, 'delete_selected')

    def test_times_are_typed_in_utc(self):
        self.client.post(self.url, event_form(
            self.workshop, starts_at_1='15:00',
            ends_at_1='17:00',
        ))
        self.workshop.refresh_from_db()
        self.assertEqual(
            self.workshop.starts_at,
            datetime(2026, 12, 3, 15, tzinfo=UTC),
        )
        response = self.client.get(self.url)
        self.assertContains(
            response, 'Thu 03 Dec 2026, 20:30 IST'
        )

    def test_rule_messages_reach_the_page(self):
        for changes, message in [
            ({'capacity': 0},
             'Capacity must be more than 0.'),
            ({'ends_at_1': '08:00'},
             'An event must end after it starts.'),
            ({'timezone': 'Mars/Base'},
             'Mars/Base is not a known time zone.'),
        ]:
            form = event_form(self.workshop, **changes)
            response = self.client.post(self.url, form)
            self.assertContains(response, message)
        self.workshop.refresh_from_db()
        self.assertEqual(self.workshop.capacity, 40)

    def test_registrations_are_read_only_history(self):
        with self.assertNumQueries(5):
            response = self.client.get(self.url)
        self.assertContains(response, 'sai@example.org')
        self.assertNotContains(
            response, 'name="registrations-0-status"'
        )
        forged = {
            'registrations-TOTAL_FORMS': 1,
            'registrations-INITIAL_FORMS': 1,
            'registrations-0-id': self.place.pk,
            'registrations-0-event': self.workshop.pk,
            'registrations-0-status': 'cancelled',
        }
        self.client.post(
            self.url, event_form(self.workshop, **forged)
        )
        self.place.refresh_from_db()
        self.assertEqual(self.place.status, 'active')

    def test_history_blocks_delete_drafts_may_go(self):
        response = self.client.post(
            admin_url(Event, 'delete', self.workshop.pk),
            {'post': 'yes'},
        )
        self.assertContains(response, 'Cannot delete event')
        draft = Event.objects.get(title='Spring planning')
        self.client.post(
            admin_url(Event, 'delete', draft.pk),
            {'post': 'yes'},
        )
        self.assertQuerySetEqual(
            Event.objects.all(), ['Django workshop'],
            transform=str,
        )

event_form() builds what the browser sends when someone saves an event’s page. The admin splits each date and time into two inputs, so starts_at_0 is the date and starts_at_1 the time, typed in UTC; f'{event.starts_at:%H:%M}' formats the stored time that way. The two registrations- keys belong to the registrations listed under the event, which this step adds: a list of rows on a form is a formset, and its two counts tell Django how many rows were sent.

The tests ask for five things. The list shows the draft Spring planning, the workshop’s start in Kolkata time, and 39 places left, from Chapter 22’s with_places(); html=True compares the cell as HTML rather than as text. 15:00 typed for the workshop is stored as 15:00 UTC, and the page then shows 20:30 IST. A capacity of 0, an end before the start, and an unknown time zone each show Chapter 21’s message and save nothing. The workshop’s page lists Sai’s registration in five queries, and a forged form that tries to cancel it changes nothing. And an event with registrations cannot be deleted, while a draft with none can. Run them:

uv run python manage.py test events.tests.EventAdminTests

Expected result, shortened with ...:

Found 5 test(s).
...
EEEEE
...
ERROR: test_history_blocks_delete_drafts_may_go (events.t...
...
...NoReverseMatch: Reverse for 'events_event_change' not ...
...
FAILED (errors=5)
Destroying test database for alias 'default'...

Five errors, all NoReverseMatch, for the same reason: the admin has no event pages yet. Now replace the whole of events/admin.py with:

"""Admin pages for events and their organizers."""
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError

from django.contrib import admin
from django.utils import timezone

from registrations.models import Registration

from .models import Event

UTC_HELP = "In UTC, not the event's own time zone."


class RegistrationInline(admin.TabularInline):
    """An event's registrations, shown as history."""

    model = Registration
    fields = ['member', 'status', 'registered_at',
              'cancelled_at']
    readonly_fields = fields
    extra = 0
    can_delete = False

    def has_add_permission(self, request, obj=None):
        """Members register on the site, not here."""
        return False

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

    def get_queryset(self, request):
        """Fetch each registration's member at once."""
        queryset = super().get_queryset(request)
        return queryset.select_related('member')


@admin.register(Event)
class EventAdmin(admin.ModelAdmin):
    """Events, with local start times and places left."""

    list_display = ['title', 'status', 'start_utc',
                    'local_start', 'places', 'capacity']
    list_filter = ['status']
    search_fields = ['title', 'location']
    ordering = ['-starts_at']
    fields = ['title', 'status', 'starts_at', 'ends_at',
              'timezone', 'local_start', 'location',
              'capacity']
    readonly_fields = ['local_start']
    inlines = [RegistrationInline]
    actions = None

    def get_queryset(self, request):
        """Count places left in the same query."""
        queryset = super().get_queryset(request)
        return queryset.with_places()

    def get_form(self, request, obj=None, **kwargs):
        """Say on the form that both times are in UTC."""
        kwargs['help_texts'] = {
            'starts_at': UTC_HELP, 'ends_at': UTC_HELP,
        }
        return super().get_form(request, obj, **kwargs)

    @admin.display(description='Start (UTC)',
                   ordering='starts_at')
    def start_utc(self, event):
        """Return the start as stored, in UTC."""
        return event.starts_at

    @admin.display(description='Local start')
    def local_start(self, event):
        """Return the start in the event's zone, or None."""
        try:
            zone = ZoneInfo(event.timezone)
        except (ValueError, ZoneInfoNotFoundError):
            return None
        if event.starts_at is None:
            return None
        local = timezone.localtime(event.starts_at, zone)
        return local.strftime('%a %d %b %Y, %H:%M %Z')

    @admin.display(description='Places left',
                   ordering='places_left')
    def places(self, event):
        """Places left, counted by the queryset."""
        return event.places_left

Read it from the bottom class up. EventAdmin’s list shows six columns. Three are fields; start_utc, local_start, and places are methods, and @admin.display gives each a column heading and, through ordering, lets the heading sort the list. get_queryset() starts every event page from with_places(), so the places come from Chapter 22’s single annotated query rather than a count per row. ordering = ['-starts_at'] lists the latest events first, which is what an administrator checks most. fields sets the change page’s order and includes local_start, which readonly_fields shows as text. get_form() passes help text for the two time fields to the form Django builds, without changing the model, so no migration is needed. actions = None removes the bulk actions above the list, including “Delete selected”.

local_start() converts the stored instant into the event’s zone with timezone.localtime() and formats it: %a %d %b %Y, %H:%M %Z gives “Thu 03 Dec 2026, 14:30 IST”. It returns None, which the admin shows as -, for an event not yet saved and for a zone that does not exist, so that a page showing “Mars/Base is not a known time zone.” can still display, rather than failing inside the conversion.

RegistrationInline is an inline: a list of related rows, here an event’s registrations, shown on the parent’s page. TabularInline shows one row per registration. Every field is read-only, extra = 0 adds no empty rows, can_delete = False removes the delete boxes, and the two permission methods refuse adding and changing, so registrations are visible here and nothing more. get_queryset() joins each registration’s member into the same query; without it, every row would run one more query to show the member’s email, the N+1 pattern Chapter 20 fixed.

Run the event tests and the access tests:

uv run python manage.py test events config

Expected result, shortened with ...:

Found 47 test(s).
...
...............................................
...
Ran 47 tests in ...

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

Now look in the browser. Reload the admin’s index: a new section, “Events”, lists the Events model with Add and Change links. Open Events. The list shows four events, the latest first, with a filter by status and a search box. Spring planning and the Winter social are drafts, which no visitor can see, and the administrator can: Chapter 22 kept Event.objects unfiltered for this reason. The Django workshop’s row shows “Dec. 3, 2026, 9 a.m.” in the “Start (UTC)” column, “Thu 03 Dec 2026, 14:30 IST” as its local start, and 59 places left of 60.

Open the Django workshop. Under each time field is the help text “In UTC, not the event’s own time zone.”, and, if your computer’s zone is not UTC, the admin’s own note about the difference. “Local start” shows 14:30 IST, and under the form, the Registrations section lists Sai’s place with no inputs. Change the capacity to 0 and press Save. The page returns with “Please correct the error below.” and Chapter 21’s message, “Capacity must be more than 0.”, and nothing is saved. Change it back to 60 without saving: press the browser’s Back button, or open the event again from the list. From Chapter 25, the admin also refuses a capacity below the places already taken, with its message beside Capacity, because that rule lives in the model.

Common Error: a time typed in the event’s own zone

Sam asks for the workshop to start at 15:00 Kolkata time, and someone types 15:00 into Starts at. The admin reads it as 15:00 UTC, so after saving, the list shows “Thu 03 Dec 2026, 20:30 IST”, and the public page shows 20:30. The “Local start” column is there so this is noticed at once. Work out the UTC time first: 15:00 in Kolkata is 09:30 UTC, five and a half hours earlier. test_times_are_typed_in_utc keeps the behaviour visible, and Chapters 27 and 28 add each person’s own zone.

Step 5: Registrations and organizer assignments

Registrations are history: the administrator may read them and nothing else, so that a place is only ever created or cancelled by the rules Chapters 31 and 33 will build. Organizer assignments carry Chapter 2’s requirement PR-6: the administrator grants organizer access by adding an assignment and removes it by revoking, setting revoked_at, never by deleting the row. Write both sets of tests first. Add a function and a class at the end of events/tests.py:

def revoke_form(when):
    """Build the post that revokes an assignment at when."""
    return {'revoked_at_0': f'{when:%Y-%m-%d}',
            'revoked_at_1': f'{when:%H:%M:%S}'}


class OrganizerAssignmentAdminTests(TestCase):
    """Assign and revoke organizers; never delete."""

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

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

    def add(self):
        """Assign Sai to the event through the admin."""
        return self.client.post(
            admin_url(OrganizerAssignment, 'add'),
            {'event': self.event.pk, 'member': self.sai.pk},
        )

    def test_add_and_revoke_but_never_delete(self):
        self.add()
        assignment = OrganizerAssignment.objects.get()
        change = admin_url(OrganizerAssignment, 'change',
                           assignment.pk)
        tomorrow = timezone.now() + timedelta(days=1)
        self.client.post(change, revoke_form(tomorrow))
        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(), 1
        )

    def test_rule_messages_reach_the_page(self):
        self.add()
        self.assertContains(
            self.add(),
            'This member already organizes this event.',
        )
        assignment = OrganizerAssignment.objects.get()
        change = admin_url(OrganizerAssignment, 'change',
                           assignment.pk)
        early = datetime(2026, 1, 1, tzinfo=UTC)
        self.assertContains(
            self.client.post(change, revoke_form(early)),
            'An assignment cannot be revoked before it '
            'starts.',
        )

    def test_list_runs_a_fixed_number_of_queries(self):
        for title in ('Python meetup', 'Spring planning'):
            OrganizerAssignment.objects.create(
                event=save_event(title=title),
                member=self.sai,
            )
        with self.assertNumQueries(5):
            self.client.get(
                admin_url(OrganizerAssignment, 'changelist')
            )

The first test adds an assignment for Sai, revokes it from tomorrow, and is refused the delete page. The second asks for Chapter 21’s two messages: a second current assignment for the same member and event, and a revocation dated before the assignment started. The third creates two assignments and expects the list in five queries. Then open registrations/tests.py and add one import after from events.models import Event:

from events.tests import admin_url

Add a class at the end of the same file:

class RegistrationAdminTests(TestCase):
    """Registrations in the admin are view-only."""

    @classmethod
    def setUpTestData(cls):
        cls.sam = User.objects.create_superuser(
            'sam@example.org', display_name='Sam'
        )
        for title in ('Python meetup', 'Django workshop'):
            event = Event.objects.create(
                title=title,
                starts_at=datetime(2026, 12, 3, 9,
                                   tzinfo=UTC),
                ends_at=datetime(2026, 12, 3, 12,
                                 tzinfo=UTC),
                timezone='UTC', location='Virtual',
                capacity=40,
            )
            for name in ('Sai', 'Raj'):
                member, _ = User.objects.get_or_create(
                    email=f'{name.lower()}@example.org',
                    defaults={'display_name': name},
                )
                Registration.objects.create(
                    event=event, member=member
                )

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

    def test_history_is_view_only(self):
        place = Registration.objects.first()
        add = self.client.get(admin_url(Registration, 'add'))
        self.assertEqual(add.status_code, 403)
        change = admin_url(Registration, 'change', place.pk)
        response = self.client.get(change)
        self.assertContains(response, 'sai@example.org')
        self.assertNotContains(response, 'name="_save"')
        response = self.client.post(
            change, {'status': 'cancelled'}
        )
        self.assertEqual(response.status_code, 403)
        response = self.client.post(
            admin_url(Registration, 'delete', place.pk),
            {'post': 'yes'},
        )
        self.assertEqual(response.status_code, 403)

    def test_list_runs_a_fixed_number_of_queries(self):
        with self.assertNumQueries(6):
            self.client.get(
                admin_url(Registration, 'changelist')
            )

The class creates two events and registers Sai and Raj for each; get_or_create() returns the member saved for the first event and creates them only once. The first test checks every refusal: no add page, a read-only page with no Save, a forged change refused, and no delete. The second expects the list of four registrations in six queries. Run both apps’ tests:

uv run python manage.py test events registrations

Expected result, shortened with ...:

Found 55 test(s).
...
ERROR: test_add_and_revoke_but_never_delete (events.tests...
...
...NoReverseMatch: Reverse for 'events_organizerassignmen...
...
ERROR: test_history_is_view_only (registrations.tests.Reg...
...
FAILED (errors=5)
Destroying test database for alias 'default'...

Five new tests error with NoReverseMatch, for the reason by now familiar: there are no pages yet. Replace the whole of registrations/admin.py with:

"""Admin pages for registrations."""
from django.contrib import admin

from .models import Registration


@admin.register(Registration)
class RegistrationAdmin(admin.ModelAdmin):
    """Registrations as history: view only."""

    list_display = ['event', 'member', 'status',
                    'registered_at', 'cancelled_at']
    list_filter = ['status', 'event']
    search_fields = ['member__email', 'event__title']
    list_select_related = ['event', 'member']

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

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

    def has_delete_permission(self, request, obj=None):
        """History is never deleted."""
        return False

The three permission methods return False for everyone, so the list’s heading becomes “Select registration to view”, each registration’s page is a view page with a Close button, and no add or delete is offered. list_display names event and member, whose text comes from rows in other tables, so list_select_related joins both into the list’s query. Django does the same on its own when the columns are related fields, but only while they are; the setting states the intent, and the query-count test guards it. search_fields uses member__email, the lookup syntax Chapter 19 used in filter(), to search across the relation.

Then open events/admin.py. Replace the import of the event model, from .models import Event, with:

from .models import Event, OrganizerAssignment

And add a class at the end of the file:

@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']

    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, only the revoke time may change."""
        if obj is None:
            return []
        return ['event', 'member', 'assigned_at']

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

get_fields() and get_readonly_fields() receive the assignment being shown, or None on the add page. Adding asks only for the event and the member; assigned_at takes its default, the moment of saving. On an existing assignment, the event, the member, and assigned_at are read-only, so the only thing the administrator can change is revoked_at: an assignment is revoked, never rewritten to mean someone else. EmptyFieldListFilter adds a filter on whether revoked_at is empty, which here means current or revoked. Delete is refused for everyone. Run the tests again:

uv run python manage.py test events registrations

Expected result, shortened with ...:

Found 55 test(s).
...
ERROR: test_rule_messages_reach_the_page (events.tests.Or...
...
django.db.utils.IntegrityError: UNIQUE constraint failed:...
...
FAILED (errors=1)
Destroying test database for alias 'default'...

Every page exists now, and one test still errors, not with Chapter 21’s message but with an IntegrityError: the database refused the second assignment, and the admin, which expected the form to have checked it, has nothing to show but an error page. In a browser with DEBUG on, this is Django’s yellow error page; on a deployed site, a “Server Error (500)” page.

Under the Hood: why the form skipped Chapter 21’s rule

When the admin saves, the form calls full_clean() with exclude, the set of model fields that are not on the form, and full_clean() passes it on to validate_constraints(). A constraint that names an excluded field is skipped, because the value it would check may not be the value that is saved. On the add page, the form holds event and member but not revoked_at, which the “one current assignment” constraint names in its condition. On the change page, assigned_at is read-only, so the form does not hold it, and the “revoked after assigned” constraint names it. Both rules were skipped, and the database refused the rows, as it should. The rules were never at risk; the message was.

The fix belongs on the model, where Chapter 21’s rules live, and it is one method. Open events/models.py and add it inside OrganizerAssignment, after __str__(), separated by one blank line:

    def validate_constraints(self, exclude=None):
        """Check every rule, even for fields a form omits."""
        super().validate_constraints(exclude=None)

validate_constraints() is the model method full_clean() calls for constraints. This version ignores the form’s exclude and checks every constraint against the values the row will actually have, including the ones the form does not hold, such as assigned_at loaded from the database. It is a method, not a field, so makemigrations has nothing to record. Run the tests once more:

uv run python manage.py test events registrations

Expected result, shortened with ...:

Found 55 test(s).
...
Ran 55 tests in ...

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

In the browser, open Organizer assignments: Sam’s assignment for the Python meetup is listed, with - under “Revoked at”. Open it: the event, the member, and the assignment time are text, and only “Revoked at” has inputs. Close it without saving. Now open Events, then the Python meetup, and press Delete at the bottom of the page. Instead of a confirmation, the page is headed “Cannot delete event”: deleting the meetup would delete related objects, and your account does not have permission to delete the types it lists, registration and organizer assignment. That refusal comes from this step’s permission methods. Underneath it, Chapter 20’s PROTECT would refuse too, so the meetup’s history is guarded twice. A draft with no registrations or assignments can be deleted, as test_history_blocks_delete_drafts_may_go proves; do not delete yours.

Common Error: “Delete selected” removes rows without asking each one

Django adds an action called “Delete selected” to every list. It deletes all the chosen rows in one query with QuerySet.delete(), which never calls a model’s own delete() method, so any check written there is skipped. Otahque’s events turn actions off with actions = None, and registrations, assignments, and users refuse delete permission, which removes the action. If a list shows “Delete selected” where Figure 23.2 says no, the ModelAdmin is missing its has_delete_permission() method.

Step 6: Register users

Chapter 17 chose AbstractBaseUser for Otahque’s user model, and warned that the admin would need its own configuration. Django’s own UserAdmin expects a username field and forms that Otahque’s model does not have, so Otahque registers a plain ModelAdmin instead, with three limits. Accounts are created with createsuperuser or create_user() until Chapter 27 builds sign-up, so the admin has no add page. Members are never deleted, because their registrations are history; an account is switched off with is_active instead. And the page never shows or sets a password. Tests first: open accounts/tests.py and add an import above from .models import User, followed by a blank line:

from events.tests import admin_url

from .models import User

Then add a class at the end of the file:

class UserAdminTests(TestCase):
    """No adding or deleting; passwords stay hidden."""

    @classmethod
    def setUpTestData(cls):
        cls.sam = User.objects.create_superuser(
            'sam@example.org', display_name='Sam'
        )
        cls.sai = User.objects.create_user(
            'sai@example.org', 'correct horse battery',
            display_name='Sai',
        )

    def setUp(self):
        self.client.force_login(self.sam)
        self.url = admin_url(User, 'change', self.sai.pk)

    def test_no_add_and_no_delete(self):
        add = self.client.get(admin_url(User, 'add'))
        self.assertEqual(add.status_code, 403)
        response = self.client.post(
            admin_url(User, 'delete', self.sai.pk),
            {'post': 'yes'},
        )
        self.assertEqual(response.status_code, 403)

    def test_page_never_shows_or_sets_the_password(self):
        response = self.client.get(self.url)
        self.assertContains(response, 'sai@example.org')
        self.assertNotContains(response, 'name="password"')
        self.assertNotContains(response, self.sai.password)
        self.assertNotContains(response, 'is_superuser')
        self.client.post(self.url, {
            'email': 'sai@example.org',
            'display_name': 'Sai K',
            'is_active': 'on',
        })
        self.sai.refresh_from_db()
        self.assertEqual(self.sai.display_name, 'Sai K')
        self.assertTrue(
            self.sai.check_password('correct horse battery')
        )

self.sai.password is the stored hash, the long string that begins pbkdf2_sha256$, so the second test checks that neither an input called password nor the hash appears on Sai’s page, and that the superuser flag cannot be set there either. It then saves Sai’s page with a new display name and checks that her password still works. Run the tests in accounts:

uv run python manage.py test accounts

Expected result, shortened with ...:

Found 14 test(s).
...
ERROR: test_no_add_and_no_delete (accounts.tests.UserAdmi...
...
...NoReverseMatch: Reverse for 'accounts_user_change' not...
...
FAILED (errors=2)
Destroying test database for alias 'default'...

Replace the whole of accounts/admin.py with:

"""Admin pages for members and the admin's log."""
from django.contrib import admin

from .models import User


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

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

UserAdmin here is Otahque’s own class, a plain ModelAdmin; it does not use Django’s class of the same name in django.contrib.auth.admin. fields lists what the page shows, and leaves out password and is_superuser entirely: a field that is not listed is not on the form, so it can be neither seen nor changed. filter_horizontal turns the groups and permissions lists into two boxes, available and chosen, with a filter above each, which is easier to use than one long list. last_login and date_joined are read-only facts. Run the tests:

uv run python manage.py test accounts

Expected result, shortened with ...:

Found 14 test(s).
...
Ran 14 tests in ...

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

Reload the admin’s index: Users now appears under “Accounts” with a Change link and no Add link. Open Users, then Sai: her email, display name, the two flags, the groups and permissions boxes, and the two dates, and no password anywhere. The administrator never needs to see a password hash, and a hash shown on every superuser’s screen is one more copy to leak. Sam can still change his own password: the header’s “Change password” link opens the admin’s password form for the signed-in account, which asks for the old password first. Changing another member’s password belongs to the password reset pages of Chapter 29.

Common Error: registering the user model with Django’s UserAdmin

Many tutorials register a custom user with admin.site.register(User, UserAdmin), importing UserAdmin from django.contrib.auth.admin. That works for users built on AbstractUser, which keep username. For Otahque’s model, every command stops with system check errors, beginning <class 'django.contrib.auth.admin.UserAdmin'>: (admin.E033) The value of 'ordering[0]' refers to 'username', which is not a field of 'accounts.User'.. Use the ModelAdmin above.

Step 7: The audit log

Since Step 4, every save you made through the admin has written a LogEntry row, even though no page lists them. The last tests prove that the right things are logged, and that the log itself is read-only. Open config/tests.py again and replace its imports with this longer version:

from datetime import timedelta
from io import StringIO

from django.contrib.admin.models import CHANGE, LogEntry
from django.contrib.auth.models import Permission
from django.core.management import call_command
from django.test import TestCase
from django.urls import reverse
from django.utils import timezone

from accounts.models import User
from events.models import Event, OrganizerAssignment
from events.tests import (
    admin_url, event_form, revoke_form, save_event,
)

PASSWORD = 'correct horse battery'
REFUSED = (
    'Please enter the correct email address and password '
    'for a staff account.'
)

Then add a class at the end of the file:

class AuditLogTests(TestCase):
    """Admin saves are logged; the log is read-only."""

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

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

    def edit_location(self):
        """Change the event's location through the admin."""
        self.client.post(
            admin_url(Event, 'change', self.event.pk),
            event_form(self.event, location='Room 2'),
        )

    def test_admin_changes_are_logged(self):
        self.edit_location()
        tomorrow = timezone.now() + timedelta(days=1)
        self.client.post(
            admin_url(OrganizerAssignment, 'change',
                      self.assignment.pk),
            revoke_form(tomorrow),
        )
        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, 'Changed Revoked at.')],
        )

    def test_log_cannot_be_edited(self):
        self.edit_location()
        entry = LogEntry.objects.get()
        add = self.client.get(admin_url(LogEntry, 'add'))
        self.assertEqual(add.status_code, 403)
        change = admin_url(LogEntry, 'change', entry.pk)
        response = self.client.get(change)
        self.assertContains(response, 'Python meetup')
        self.assertNotContains(response, 'name="_save"')
        self.assertEqual(
            self.client.post(change, {}).status_code, 403
        )
        response = self.client.post(
            admin_url(LogEntry, 'delete', entry.pk),
            {'post': 'yes'},
        )
        self.assertEqual(response.status_code, 403)
        self.assertEqual(LogEntry.objects.count(), 1)

The first test changes an event’s location through the admin, revokes an assignment, and expects two log entries, in order, each with Sam as the user, CHANGE as the action, and the names of the changed fields as the message. get_change_message() turns the stored message into that sentence. The second test checks that the log page refuses every way of changing an entry. Run the tests in config:

uv run python manage.py test config

Expected result, shortened with ...:

Found 8 test(s).
...
......E.
...
ERROR: test_log_cannot_be_edited (config.tests.AuditLogTe...
...
...NoReverseMatch: Reverse for 'admin_logentry_add' not f...
...
FAILED (errors=1)
Destroying test database for alias 'default'...

The first test passes already, because Django has been writing the log since Step 4; only the page is missing. Open accounts/admin.py and replace its imports, the two lines before the class, with:

from django.contrib import admin
from django.contrib.admin.models import LogEntry

from .models import User

And add a class at the end of the file:

@admin.register(LogEntry)
class LogEntryAdmin(admin.ModelAdmin):
    """The admin's change log, read-only."""

    list_display = ['action_time', 'user', 'content_type',
                    'object_repr', 'action_flag', 'message']
    list_filter = ['action_flag', 'content_type', 'user']
    search_fields = ['object_repr', 'change_message']
    list_select_related = ['user', 'content_type']

    @admin.display(description='Message')
    def message(self, entry):
        """Return the change message in plain words."""
        return entry.get_change_message()

    def has_add_permission(self, request):
        """Only the admin itself writes the log."""
        return False

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

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

The audit log’s admin class lives in accounts/admin.py for a practical reason: autodiscover() reads admin.py only from installed apps, and config is not one. The log records what accounts did, so the accounts app owns its page. Every permission method returns False, so the page is read-only for everyone. The filters choose the action, the kind of object, and the account; list_select_related joins the account and the kind of object, which every row shows. Run the tests:

uv run python manage.py test config

Expected result, shortened with ...:

Found 8 test(s).
...
Ran 8 tests in ...

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

Now make a real correction and read its record. The library has confirmed Room 2 for Spring planning. In the browser, open Events, then Spring planning, change Location to Leeds Central Library, Room 2, and press Save. The list returns with “The event “Spring planning” was changed successfully.” Reload the index: “Log entries” is listed under “Administration”, with a View link only, and the index’s “Recent actions” box shows the change. Open Log entries: one row, with the time, sam@example.org, “Events | event”, “Spring planning”, “Change”, and the message “Changed Location.”. Then open Spring planning again and press History: the same entry, from the event’s side.

Common Error: the log page never appears

A config/admin.py holding the log’s admin class is never imported, because config is not an installed app, so the index has no Log entries and the log tests fail with NoReverseMatch, meaning the admin has no page by that name. Keep the class in an installed app’s admin.py, as above.

The log answers “who changed what, through the admin, and when”. Figure 23.4’s other column still holds: the shell session in Chapter 22 and the scripts of earlier chapters left no entries, and neither will Otahque’s own pages. Chapters 30 and 65 plan the audit trail that records Otahque’s important actions wherever they happen.

Step 8: Record the boundary

The configuration is in the code; the reasons belong in a design note that the next developer reads before changing it. Create docs/design/admin.md, beside Chapter 15’s ERD:

# Otahque admin site

Status: Drafted in Chapter 23, for review.
Who: the community administrator only. Organizers use
Otahque's own pages (Chapter 26); visitors and members
never use the admin site.

## What the admin may do

- Events: view, add, and change; delete only an event
  with no registrations or assignments; no bulk actions.
  Times are typed in UTC; the list and the event page
  show the local start in the event's own zone.
- Registrations: view only. Places are created and
  cancelled by Otahque's own pages (Chapters 31, 33).
- Organizer assignments: view, add, and revoke by
  setting revoked_at; never deleted (PR-6).
- Users: view and change email, display name, active,
  staff, groups, and permissions. 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.
- Log entries: view only. The audit log of admin saves.

## What the admin does not protect

- 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: Chapters 30, 65.
- Permissions are per model, not per event, so the
  admin cannot limit an account to its own events.
- A rule that is not in the model is not applied here.

## Best practices

- Done (Chapter 23): admin path from DJANGO_ADMIN_URL,
  not the guessable admin/, in each deployment.
- Done (Chapter 23): per-model limits in code, each
  proved by a test, superusers included.
- Done (Chapter 23): password never shown or set on
  the user page.
- Done (Chapter 23): read-only audit log page.
- Planned (Chapter 30): an administrator group with
  only the permissions the role needs; no shared
  superuser accounts.
- Planned (Chapters 29, 59): two-factor sign-in,
  required for staff, through django-allauth's MFA.
- Planned (Chapters 59, 60): sign-in rate limits,
  HTTPS only, secure cookies, and security headers.
- Planned (Chapter 63): deployment review of the admin
  path, staff accounts, and access logs.
- Rule: the superuser password is used locally only;
  deployed accounts are created per person.

The second half is a checklist of admin best practices, each marked with where it stands. Four are done in this chapter, and the rest are planned for the chapters named. Writing down what is not done yet is part of the design: “the admin site is safe” would be a claim nobody can check, and this list can be.

Step 9: Review and commit

Run every test:

uv run python manage.py test

Expected result, shortened with ...:

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

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

Confirm that no model change needs a migration. The new method on OrganizerAssignment is code, not schema:

uv run python manage.py makemigrations --check --dry-run
No changes detected

Look at what changed:

git status --short
 M .env.example
 M accounts/admin.py
 M accounts/tests.py
 M config/settings.py
 M config/tests.py
 M config/urls.py
 M events/admin.py
 M events/models.py
 M events/tests.py
 M registrations/admin.py
 M registrations/tests.py
?? docs/design/admin.md

Eleven changed files and one new file. .env is not listed, because Chapter 8’s .gitignore keeps it out of Git. Your correction to Spring planning is a row in your database, not a file, so Git does not see it either. Commit:

git add .env.example accounts config docs
git add events registrations
git commit -m "Configure the admin site"

When something goes wrong

Table 23.2 — Admin problems and safe recovery
Symptom Likely cause Safe recovery
The index lists only Groups No model registered yet, or admin.py not saved Expected before Step 4; check @admin.register
Please enter the correct email address and password for a staff account Wrong password, or an account without is_staff or is_active For Sam's password: uv run python manage.py changepassword sam@example.org
ImproperlyConfigured: DJANGO_ADMIN_URL must end with / The value has no final slash, or starts with / Fix .env, or the variable in your shell
Page not found at /admin/ DJANGO_ADMIN_URL set to another path Open the path from your .env
FAILED (errors=2), NoReverseMatch, in Step 3 Events not registered yet Expected; continue with Step 4
IntegrityError in Step 5 A constraint skipped for a field the form omits Expected; add validate_constraints()
A time an event appears hours off Typed in the event's zone, read as UTC Convert to UTC first; check Local start
Local start shows - Event not saved yet, or an unknown zone Save a valid zone
assertNumQueries: more queries than expected A related row read per row list_select_related, or select_related in get_queryset()
admin.E033 about username Django's UserAdmin used for Otahque's user Use the plain ModelAdmin of Step 6
No Log entries on the index The class is in config/admin.py Move it to accounts/admin.py
Cannot delete event The event has registrations or assignments Expected: history is kept
makemigrations reports changes A field changed by mistake Compare with git diff; undo the change
PAGE 003

Verify Your Work

Work through Table 23.3 from the folder that holds manage.py. The test rows come first: they hold the admin’s limits in place, whatever rows your database holds.

Table 23.3 — Verification checklist for Chapter 23
Check Command or action Expected result
Access tests red first The Step 3 run, before events are registered Found 6 test(s); FAILED (errors=2)
Rule messages need the model The Step 5 run, before validate_constraints() FAILED (errors=1), IntegrityError
Tests pass uv run python manage.py test Found 77 test(s); OK
No migration needed makemigrations --check --dry-run No changes detected
Address from settings DJANGO_ADMIN_URL=admin in .env, then check ImproperlyConfigured; restore admin/
Event list Sign in; open Events Four events, drafts included, latest first; Start (UTC), Local start, Places left
Rules reach the page Capacity 0 on the workshop, Save Capacity must be more than 0; nothing saved
History kept Delete on the Python meetup Cannot delete event
Registrations Open one View page with Close, no Save
User page Open Sai No password, no superuser flag
Audit log Log entries Changed Location. for Spring planning
Committed git status --short No output
Not verified macOS, Linux, WSL; PostgreSQL Readers on those systems; Chapter 32

Restore DJANGO_ADMIN_URL=admin/ straight after the address check. The commands were checked in Windows PowerShell 5.1 and Git Bash, and the browser rows in Microsoft Edge against the development server, with the browser set to the Kolkata time zone to see the admin’s own time note.

PAGE 004

Checkpoint: Quiz and Challenge

Quiz

Que. 2 An account has is_staff set and holds no permissions. What does it see after signing in to the admin site, and does it organize any event?

Flip to check your answerFold answer back

Answer. The index says it has no permission to view or edit anything, and every model page refuses it with 403. It organizes nothing: organizing is an OrganizerAssignment row, which is_staff does not create, and only Otahque’s own pages will read it.

Que. 3 Sam types 18:30 into the Starts at field of the Python meetup in Leeds, for a date in July. What is stored, and what does a visitor see?

Flip to check your answerFold answer back

Answer. The admin reads the time in the current zone, UTC, so 18:30 UTC is stored. In July, Leeds is on British Summer Time, one hour ahead of UTC, so the public page shows 19:30. The Local start column would show 19:30 BST and reveal the mistake.

Que. 4 Why did RegistrationAdmin refuse change permission, when Sam is a superuser who holds every permission?

Flip to check your answerFold answer back

Answer. A has_change_permission() method that returns False refuses the action for every account, superusers included. Registrations are history: places are made and cancelled by the rules of Chapters 31 and 33, so the admin may only read them.

Que. 5 In Step 5, adding a second current assignment raised IntegrityError instead of showing Chapter 21’s message. Why, and what changed?

Flip to check your answerFold answer back

Answer. The add page’s form holds event and member but not revoked_at, which the “one current assignment” constraint names, so full_clean() skipped the constraint, and the database refused the row. OrganizerAssignment.validate_constraints() now checks every constraint, whatever the form holds, so the message appears on the page.

Que. 6 Which of these appear in the audit log: a location changed in the admin, a registration created in the shell, and Sam signing in?

Flip to check your answerFold answer back

Answer. Only the location change. The log records adds, changes, and deletes made through the admin’s pages; the shell and sign-ins write nothing there.

Mini-Challenge

Que. 7 The community plans to give a second administrator an account that may only read registrations and the audit log. Predict which models the admin index will list for an account with is_staff and the two permissions view_registration and view_logentry, and whether it may open the registration list and the event list. Then check your prediction with a practice file that creates the account inside a transaction and rolls it back.

Flip to check your answerFold answer back

Answer. The index lists Log entries and Registrations, each with a View link. The account may open the registration list, and the event pages refuse it with 403. One file that checks it, run with uv run python ../practice/challenge.py:

import setup_django
from django.contrib import admin
from django.contrib.auth.models import Permission
from django.db import transaction
from django.test import RequestFactory

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

CODES = ['view_registration', 'view_logentry']
with transaction.atomic():
    reader = User.objects.create_user(
        'reader@example.org', display_name='Reader',
        is_staff=True,
    )
    reader.user_permissions.add(
        *Permission.objects.filter(codename__in=CODES)
    )
    request = RequestFactory().get('/')
    request.user = User.objects.get(pk=reader.pk)
    print([model['name']
           for app in admin.site.get_app_list(request)
           for model in app['models']])
    for model in (Registration, Event):
        model_admin = admin.site.get_model_admin(model)
        allowed = model_admin.has_view_permission(request)
        print(model.__name__, allowed)
    transaction.set_rollback(True)
kept = User.objects.filter(email='reader@example.org')
print(kept.exists())
['Log entries', 'Registrations']
Registration True
Event False
False

get_app_list() is the list the index page draws, so its model names are what the account sees, and has_view_permission() is the check each list page makes before it opens. The account is fetched again before the checks because Django caches an account’s permissions the first time it asks. transaction.atomic() with set_rollback(True) undoes the account and its permissions, so the last line confirms nothing was kept.

What We Learned

  • The admin site is the administrator’s tool, built from the models; Otahque’s own pages serve visitors, members, and organizers.
  • is_staff only lets an account sign in to the admin. Permissions decide each page, and organizing is an assignment row, not a flag.
  • A ModelAdmin chooses list columns, filters, search, order, and fields; @admin.display adds computed columns.
  • has_add_permission() and its siblings state rules for every account, superusers included, and each refusal deserves a test.
  • Times typed in the admin are read in the current zone, UTC; label the fields and show the local time beside them.
  • The admin’s forms call full_clean(), so model rules reach the page, but a constraint naming a field the form omits is skipped unless the model checks it.
  • Related columns, inlines, and lists need joined queries; assertNumQueries keeps each page’s count fixed.
  • History stays read-only: registrations are viewed, assignments revoked, users deactivated, and “Delete selected” is removed.
  • LogEntry records admin saves only; a read-only page makes it Otahque’s audit log, and a business trail comes later.
  • The admin’s address belongs in settings, read from the environment, and its remaining risks belong in a design note.

Key terms

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

Table 23.4 — Key terms from Chapter 23
Term Meaning
Admin site Django's built-in application for viewing and editing registered models.
Administrator The person who looks after the whole community, through the admin site.
ModelAdmin A class describing the admin pages for one model.
Registration (admin) Pairing a model with its ModelAdmin, as @admin.register does.
is_staff The flag that lets an active account sign in to the admin site.
Model permission add, change, delete, or view for one model, held directly or through a group.
Group A named set of permissions given to accounts together.
Inline Related rows shown on a parent's admin page.
Formset A list of forms of the same kind submitted together.
ModelForm A form generated from a model's fields.
Current time zone The zone Django reads typed times in; UTC unless activated.
LogEntry One row of the admin's change history.
Audit log Otahque's read-only page listing LogEntry rows.

Readiness checkpoint: you are ready for Chapter 24 when all 77 tests pass, makemigrations --check --dry-run prints No changes detected, the admin site at your DJANGO_ADMIN_URL lists Events, Organizer assignments, Registrations, Users, and Log entries with the limits of Figure 23.2, Spring planning’s location change appears in the audit log, and git status --short prints nothing. Chapter 24 writes forms of its own, starting with the ModelForm that the admin built for you here. Return to the relevant step if any result is missing.

Git Commit

Your Chapter 23 work was committed in Step 9. For the record, these were the commands, in any of the four shells, beside manage.py:

git add .env.example accounts config docs
git add events registrations
git status --short
M  .env.example
M  accounts/admin.py
M  accounts/tests.py
M  config/settings.py
M  config/tests.py
M  config/urls.py
A  docs/design/admin.md
M  events/admin.py
M  events/models.py
M  events/tests.py
M  registrations/admin.py
M  registrations/tests.py
git commit -m "Configure the admin site"

The commit holds the admin’s address setting and its example, the URL configuration, four admin classes and an inline in three admin.py files, the audit log’s admin class, one model method, nineteen new tests, and the design note. There is no migration, because no field changed.

PAGE 005

Test Your Knowledge: Interview Questions

These five questions rehearse the chapter at interview level, one at each of five levels from junior to lead. L1 to L3 check what you have just done. L4 and L5 look ahead to a larger application with a team: attempt them now, and return to them after Chapters 26, 30, and 57. They are extension questions, not a gate to the next chapter. Each code proof is a short file in the practice folder that starts by importing Chapter 16’s setup_django.py; run it from the folder that holds manage.py with uv run python ../practice/ followed by the file name. The proofs only read your rows: any row they create is rolled back.

L1 (Junior): What is the Django admin site for, and who should use it?

What the interviewer is testing: Do you know the admin’s purpose, how a model gets into it, and who it is not for?

Flip to check your answerFold answer back

Perfect answer: The admin site is Django’s built-in tool for viewing and editing the data of registered models, for the people who run an application, not for its users. I register each model with a ModelAdmin in the app’s admin.py, and choose its columns, filters, search, and what may be added, changed, or deleted. Only active accounts with is_staff can sign in, and permissions decide what each one sees. In Otahque, the community administrator uses it to check rows and make corrections, such as granting or revoking organizer access. Members and organizers use Otahque’s own pages, because their work has rules about ownership that the admin does not check per event. I keep every important rule in the model, so it applies in the admin too, and I test the admin’s limits.

Table 23.5 — The admin site and Otahque’s own pages compared
Aspect Admin site Otahque's pages
Who The administrator Visitors, members, organizers
Built from Models and ModelAdmin classes Views and templates we write
Access is_staff and model permissions Sign-in and ownership rules

Behind the scenes:

admin.py + @admin.register -> pages built from the model
is_active and is_staff     -> may sign in
model permissions          -> what each page allows
full_clean()               -> model rules on every save

Code proof: which models are registered, and which accounts may sign in:

import setup_django
from django.apps import apps
from django.contrib import admin

from accounts.models import User

for model in apps.get_models():
    if admin.site.is_registered(model):
        print(model._meta.label)
staff = User.objects.filter(is_staff=True)
print(list(staff.values_list('email', flat=True)))
admin.LogEntry
auth.Group
accounts.User
events.Event
events.OrganizerAssignment
registrations.Registration
['sam@example.org']

Every model with an admin page, in the order of INSTALLED_APPS, and the one staff account on your computer: Sam’s, from Chapter 18.

Common mistakes:

  • Building members’ or organizers’ pages in the admin because it is quick.
  • Leaving business rules out of the model, so the admin skips them.
  • Treating the admin’s address as its security.

Follow-up the interviewer might ask:

  • “Why does Django not register LogEntry with the admin by default?”
  • “How would you find which admin class a model uses?”

L2 (Mid-Level): Why is a staff flag not a role, and how would you prove it in Otahque?

What the interviewer is testing: Can you separate Django’s access flags from the application’s own roles, and prove the separation?

Flip to check your answerFold answer back
Five numbered steps. is_staff lets an account sign in to the admin site. Permissions decide every page; none means nothing. Organizing is a row: an organizer assignment. Staff without permissions sees nothing and organizes nothing. Prove it with a test, not a promise.
Figure 23.5 — Why the staff flag is not the organizer role.

Perfect answer: is_staff answers one question: may this account sign in to the admin site? It grants no page by itself; each page needs a model permission, and is_superuser grants them all. A role, such as an Otahque organizer, is a product idea with its own rules: it applies to particular events, it is granted and revoked by the administrator, and its history is kept. That is why Otahque stores it as an OrganizerAssignment row, and why Otahque’s own pages, not the admin’s flags, will decide what an organizer may do. Using is_staff as the organizer role would let every organizer into the admin and, with a permission, into every event. I prove the separation with a test: a staff account with no permissions sees “no permission to view or edit anything”, gets 403 on the event list, and holds no assignment.

Behind the scenes:

is_staff              -> sign in to the admin only
model permission      -> one action on one model
is_superuser          -> every permission
OrganizerAssignment   -> organizes one event

Code proof: a staff account with nothing else, created and rolled back:

import setup_django
from django.contrib import admin
from django.db import transaction
from django.test import RequestFactory

from accounts.models import User

with transaction.atomic():
    helper = User.objects.create_user(
        'helper@example.org', display_name='Helper',
        is_staff=True,
    )
    request = RequestFactory().get('/')
    request.user = helper
    print(admin.site.has_permission(request))
    print(admin.site.get_app_list(request))
    print(helper.organizer_assignments.exists())
    transaction.set_rollback(True)
kept = User.objects.filter(email='helper@example.org')
print(kept.exists())
True
[]
False
False

It may sign in, it sees no models, and it organizes no event; the last line shows that the rollback left no account behind.

Common mistakes:

  • Ticking is_staff to make someone an organizer.
  • Giving every staff account is_superuser to save time.
  • Testing that the right person gets in, but not that others stay out.

Follow-up the interviewer might ask:

  • “Where should Otahque check that an organizer may edit an event?”
  • “How would you give the administrator exactly the permissions the role needs?”

L3 (Senior): An event appears hours off on the public page after someone edited it in the admin. What happened, and what do you change?

What the interviewer is testing: Do you understand how typed times are interpreted with USE_TZ, and can you fix the cause rather than the symptom?

Flip to check your answerFold answer back
Five numbered steps. 15:00 typed for the Kolkata workshop. The form reads it in the current zone: UTC. Stored as 15:00 UTC, which is 20:30 IST. Local start shows the mistake at once. Label the fields; per-person zones in Chapters 27 and 28.
Figure 23.6 — How a time typed in the admin goes wrong, and how Otahque shows it.

Perfect answer: With USE_TZ on, Django stores aware datetimes in UTC and reads every typed time in the current time zone, which is TIME_ZONE unless code activates another. Otahque’s TIME_ZONE is UTC, so 15:00 typed for the workshop in Kolkata became 15:00 UTC, which the public page, showing the event’s own zone, displays as 20:30. Nothing was corrupted; the person and the form meant different zones. The immediate fix is to correct the time, typed in UTC. The lasting fixes are to make the zone visible, as Otahque does with help text and a Local start column, and to read typed times in a zone the person chose: Chapter 28 activates each person’s zone for every request, and from Chapter 24 Otahque’s own event form reads typed times in the event’s own zone. I would not change the stored values to local times: one zone in storage keeps comparisons and sorting correct.

Behind the scenes:

USE_TZ = True     -> stored in UTC
TIME_ZONE = 'UTC' -> typed times read as UTC
activate(zone)    -> typed times read in that zone
display           -> converted to the event's zone

Code proof: the same text, read in UTC and in Kolkata’s zone:

import setup_django
from zoneinfo import ZoneInfo

from django import forms
from django.utils import timezone

field = forms.DateTimeField()
typed = '2026-12-03 15:00'
as_utc = field.clean(typed)
with timezone.override(ZoneInfo('Asia/Kolkata')):
    as_kolkata = field.clean(typed)
print(as_utc)
print(as_kolkata)
print(as_utc - as_kolkata)
2026-12-03 15:00:00+00:00
2026-12-03 15:00:00+05:30
5:30:00

timezone.override() activates a zone for the block, as Chapter 28’s middleware will for each request. The same text means two instants, five and a half hours apart.

Common mistakes:

  • Storing local times in the database to make the admin “look right”.
  • Setting TIME_ZONE to the administrator’s own zone, which is wrong for every event elsewhere.
  • Fixing the one event and leaving the form unlabelled.

Follow-up the interviewer might ask:

  • “Which zone should an organizer’s form use: the organizer’s, or the event’s?”
  • “What happens to a time typed during the hour that a clock change skips?”

L4 (Staff): The admin’s registration list has become slow as Otahque grows. How do you find the cause and keep it fixed?

What the interviewer is testing: Can you trace a slow admin page to its queries, fix it with the admin’s own tools, and stop it returning?

Flip to check your answerFold answer back
Five numbered steps. A list column reads a related row. A query per row: 3 rows, 7 queries. Count the queries in a test. Join the related rows: 1 query. assertNumQueries keeps the count fixed.
Figure 23.7 — Finding and fixing a query per row in an admin list.

Perfect answer: A slow list usually means a query per row: a column whose text comes from another table, such as a registration’s __str__(), which reads its member and its event, runs two more queries for each row, so the list’s queries grow with the page size. I would confirm it by counting queries, with a query-count test or a database toolbar, rather than guessing. The fix is to join the related rows into the list’s query: list_select_related on the ModelAdmin, select_related() in get_queryset() for an inline, or an annotation for counts, as Otahque’s places column does. Django joins foreign keys named in list_display by itself, but only while they are named, so I set the joins explicitly and guard each page with assertNumQueries. If the list is still slow with a fixed number of queries, the next suspects are counting every row for the paginator, a search across relations without an index, and filters that list every related row; Chapters 56 and 57 measure those.

Behind the scenes:

__str__ reads relations -> 1 + 2 per row
list_select_related     -> joined into 1
inline get_queryset()   -> select_related
assertNumQueries        -> count stays fixed

Code proof: the registrations’ text, with and without the join:

import setup_django
from django.db import connection
from django.test.utils import CaptureQueriesContext

from registrations.models import Registration

plain = Registration.objects.all()
joined = plain.select_related('event', 'member')
for rows in (plain, joined):
    with CaptureQueriesContext(connection) as queries:
        labels = [str(row) for row in rows]
    print('rows:', len(labels), 'queries:', len(queries))
rows: 3 queries: 7
rows: 3 queries: 1

Three registrations, read plainly, cost one query for the rows and two more for each row’s event and member, seven in all; joined, one.

Common mistakes:

  • Adding database indexes before counting the queries.
  • Fixing the list but not the inline, which has its own query.
  • Removing a column instead of joining what it needs.

Follow-up the interviewer might ask:

  • “What does show_full_result_count change on a large list?”
  • “When would list_per_page or a search on an indexed field matter more than joins?”

L5 (Lead): A teammate proposes letting organizers use the admin site to manage their own events, to save building pages. What do you advise?

What the interviewer is testing: Can you weigh a shortcut against the product’s access rules, and explain the limits of model permissions?

Flip to check your answerFold answer back
Five numbered steps. Goal: organizers manage only their own events. Admin permissions are per model, not per event. change_event lets an account change every event. Per-event checks mean custom admin code to maintain. Give organizers their own pages, Chapter 26.
Figure 23.8 — Why organizers get their own pages rather than the admin site.

Perfect answer: I would start from the requirement: an organizer manages only the events they are assigned to, and only in the ways the product allows. The admin’s permissions are per model: change_event lets an account change every event, so an organizer with it could edit another organizer’s event. Restricting it means overriding get_queryset() and the permission methods to check assignments, hiding fields, and keeping all of that in step with Django’s admin across upgrades, while the admin also shows organizers a tool with more power than they need. It also makes every organizer a staff account, which mixes the two ideas Otahque keeps apart. The pages are not much saved either: an organizer needs a few focused screens, which Chapter 26 builds with forms, ownership checks, and tests. So I would keep the admin for the administrator, and build organizer pages. If time is short, the administrator can make changes on an organizer’s behalf through the admin until those pages exist, and the audit log records each change.

Behind the scenes:

change_event        -> every event, not one
per-event checks    -> custom admin code
staff organizers    -> mixes flags and roles
Chapter 26 pages    -> ownership by assignment

Code proof: an account with change_event, and no assignment, against every event:

import setup_django
from django.contrib import admin
from django.contrib.auth.models import Permission
from django.db import transaction
from django.test import RequestFactory

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

with transaction.atomic():
    helper = User.objects.create_user(
        'helper@example.org', display_name='Helper',
        is_staff=True,
    )
    helper.user_permissions.add(
        Permission.objects.get(codename='change_event')
    )
    request = RequestFactory().get('/')
    request.user = User.objects.get(pk=helper.pk)
    event_admin = admin.site.get_model_admin(Event)
    for event in Event.objects.all():
        allowed = event_admin.has_change_permission(
            request, event
        )
        print(event, allowed)
    print(helper.organizer_assignments.count())
    transaction.set_rollback(True)
Python meetup True
Django workshop True
Winter social True
Spring planning True
0

The admin would let it change all four events, although it organizes none of them: the permission names a model, not an event.

Common mistakes:

  • Treating the admin as a free front end for a role with ownership rules.
  • Adding per-object checks to the admin without tests for each refusal.
  • Making organizers staff accounts.

Follow-up the interviewer might ask:

  • “If you did restrict the admin per event, which methods would you override?”
  • “How would Chapter 30’s permissions design change your answer?”

Next: Chapter 24 writes Otahque’s own forms, starting with the ModelForm that the admin built for you in this chapter, and its validation, help text, and error messages.

PAGE 006