ContentsClose contents
Pre-release
Chapter 41 · Management commands and data import/exportCHAPTER 41

Complete six-part pre-release for review. Two migrations (Registration.source and a download audit action). Chapter 30's group test reads accounts/roles.py (declared). The PDF report is a Mini-Challenge idea only.

Working towards: Event-day operations (Chapter 46). Reminders sent in the background, a waitlist that offers released places, and check-in that records each attendance once. All milestones

CHAPTER FORTY-ONE

Management commands and data import/export

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

Prerequisites: Chapters 9 to 40, including the Chapter 40 project with its 448 passing tests, the Organizers and Administrators groups made by a data migration (Chapter 30, and Chapter 38’s addition), Event.register() with its lock and refusal codes (Chapters 31, 33, and 38), the attendee list with its fact and question columns (Chapters 31 and 38), the refusal records (Chapter 30), and the system checks (Chapter 40)

What you’ll build: Three management commands: ensure_groups, which reports and repairs the two groups; seed_demo, which makes the same sample community on every reader’s machine; and import_registrations, which gives existing members places from a spreadsheet, with a dry run and a reason for every row. Also a round trip of the data through a fixture with natural keys, a source on every place, and a streamed CSV download of the attendee table for the event’s organizers and the administrator, each download recorded, safe to open in a spreadsheet, and announced by an action bar and a personal-data notice

Why This Matters

Sam ran his last three Python clinics with a spreadsheet. The people on it are Otahque members now, and he wants them to hold places in next month’s clinic without each of them registering again. Soni, the administrator, wants a way to put the Organizers and Administrators groups right if someone changes them in the admin by mistake. Every reader of this book needs the same realistic data for the chapters on search, reports, and load. And Sam wants the attendee list as a spreadsheet for the venue’s front desk.

None of these is a page a member opens. An import is run once, by an operator, from a file on their computer; repairing groups is a fix someone runs after a mistake; sample data is made once per machine. Django’s answer for such jobs is the management command: Python code you run as manage.py something, with arguments, output, and an exit code, like migrate and check. The download is a page, but an unusual one: it returns a file, built row by row, that leaves Otahque and goes wherever Sam takes it.

Both directions carry risks this chapter takes seriously. An import must not invent accounts or consent, and must say clearly what it did with each row. A download is a copy of personal data that Otahque can no longer protect, so it is limited to the people who may see the list, recorded, and written so that no cell can run as a formula when someone opens the file.

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

  • write a management command with arguments, output, and a meaningful exit code, and test it with call_command();
  • keep data that several parts of a project need, such as a group’s permissions, in one module;
  • make deterministic sample data, and choose between fixtures, seed commands, and data migrations;
  • dump and load data with natural keys, and say what must never go into a fixture;
  • import rows through the same rules as the site, with a dry run that cannot drift from the real run;
  • stream a CSV file that is safe from formula injection, keeps phone numbers, and opens correctly in Excel.

Out of scope: uploading the spreadsheet on a page (after Chapter 44, which adds background tasks; Chapter 42 covers uploaded files), running a long import as a task (Chapter 44), retention of download records (Chapter 65), and a PDF version of the list (a Mini-Challenge idea, not built here).

PAGE 001

What You Need to Know

Management commands

New Concept: management commands

What problem exists? Some jobs are not pages: an operator runs them from a terminal, once or on a schedule, often with a file or options.

What did people do before? A Python script that set up Django by hand, a hidden page that only an administrator was meant to know, or the Django shell with pasted code.

What is it? A management command is a module in an app’s management/commands/ folder, holding a class named Command that inherits BaseCommand. Its add_arguments() declares options with Python’s argparse; its handle() does the work and writes to self.stdout. Raising CommandError prints the message and ends with exit code 1. Tests run a command with call_command('name', ...).

Why use it? It runs with the project’s settings and models, after the system checks, with arguments that are checked and documented by --help, and it can be tested like any other code.

Now let’s use it. Step 3 writes ensure_groups.

A command’s path from the terminal to its exit code is in Figure 41.1. The exit code matters more than it seems: a script, a scheduler, or CI decides what to do next from it alone. Otahque’s commands exit with 0 when all is well and 1 when something needs a person’s attention, such as a refused import row.

Five numbered cards joined by arrows. 1, uv run python manage.py import_registrations 7 people.csv: manage.py finds the command in registrations/management/commands/. 2, django.setup() and the system checks: the same start as every command. 3, add_arguments(), then argparse: event_id, csv_file, --dry-run; wrong arguments stop here with a usage line. 4, handle(): the work, writing to self.stdout; tests call it with call_command(). 5, exit code: 0 when all is well; CommandError prints the message and exits 1.
Figure 41.1 — A management command, from the terminal to its exit code.

Three kinds of data setup

Sample data, test data, and data the application cannot run without are three different needs, and Django offers a tool for each. Table 41.1 compares them; Steps 4 and 5 build two of them.

Table 41.1 — Fixtures, seed commands, and data migrations
Tool What it is Use it for Avoid it for
Fixture A file of rows that loaddata saves as they are Small, exact data in tests Real people's data; data that must follow model rules
Seed command Code that creates rows through models The same sample community for every reader Data the application needs to run
Data migration Code in a migration, run once by migrate Rows the application needs, such as groups Sample or test data

A fixture is a JSON (or YAML or XML) file written by dumpdata and read by loaddata. loaddata saves rows exactly as the file holds them: no save() method, no validation, which is why Chapter 40’s receiver saw raw=True. By default rows refer to each other by primary key, which breaks when the numbers differ between databases. Natural keys replace those numbers with values that identify a row everywhere, such as a member’s email or a permission’s app and codename: dumpdata --natural-foreign --natural-primary.

In practice: a fixture is a copy of personal data

Situation. A reader dumps the database to share a bug.

Application. The fixture holds members’ email addresses, phone numbers, answers, the audit trail, and, unless excluded, their two-factor secrets (Chapter 29). Otahque’s fixtures are made from seed_demo data, exclude mfa and sessions, and are never committed.

Consideration. dumpdata is not a backup either: Chapter 65 backs up with PostgreSQL’s own tools.

Importing without inventing

The import’s rules were decided before this chapter (D41.1 to D41.3, N41.7): a row gives a place to an existing member with a confirmed email, or it is refused with a reason; no account is created. The registration window is ignored, because the operator has decided these people should have places, but every other rule holds, capacity included. Each place made this way is marked source='import', so anyone can later tell it from a place a member took. Figure 41.2, in Step 8, shows the flow.

The dry run is where imports usually go wrong. A preview that checks rows with its own code will one day disagree with the real import. Otahque’s dry run runs the real import, every lock and every rule, inside one transaction, and then rolls the transaction back: the preview cannot drift, because it is the import.

A download that is safe to open

A CSV file is plain text, but nobody reads it as plain text: Sam opens it in Excel or LibreOffice, and they interpret cells. A cell that starts with =, +, -, or @ is read as a formula. A member who sets their display name to =HYPERLINK("http://...") puts a working link, or worse, in Sam’s spreadsheet. This is CSV injection, also called formula injection, and OWASP’s advice is to prefix such cells with an apostrophe, which spreadsheets read as “this is text”.

Two probes on Excel 16, recorded in the plan review, shape Otahque’s download. Quotes in the CSV file do not protect a cell: "=1+1" still ran as a formula. And a phone number such as +447700900123 became the number 4.48E+11, losing its plus and its digits, but +44 7700 900123, with spaces, stayed text. So Otahque guards every cell a person typed, and writes phone numbers itself, spaced, without the apostrophe. Excel also needs to be told the file is UTF-8: a byte order mark (BOM) at the start does that, or names such as Søren arrive garbled.

Under the Hood: streaming a response

HttpResponse builds the whole file in memory before sending a byte. StreamingHttpResponse takes an iterator and sends each piece as it is produced, so a list of thousands of rows never sits in memory whole. csv.writer normally writes to a file; given an object whose write() returns its argument, writerow() returns the line instead, ready to yield. The cost: middleware cannot read a streamed body, and the response has no length header.

PAGE 002

How We Build It

Start from Chapter 40, in the folder containing manage.py, with Otahque on PostgreSQL 18, 448 passing tests, and the work committed (the last commit is “Warn about unsafe settings at startup”). Two migrations are new, one in registrations and one in audit; no package changes. The new files are accounts/roles.py, three commands in management/commands/ folders of accounts, events, and registrations, registrations/table.py, five test modules, and docs/runbooks/import.md. The models, register(), the registrations views and URLs, the attendee template, Chapter 30’s group test, the stylesheet source, and four design notes change. The visible result: the attendee list has a Download CSV button and a personal-data notice, and three new commands appear in manage.py help. The chapter’s commands were checked in Windows PowerShell 5.1 and Git Bash against PostgreSQL 18.

The Custom Way

Without commands, Soni would repair a group by clicking through the admin from a list on paper, and Sam’s spreadsheet would become sixty registrations typed by hand. Step 3 turns Soni’s list into code that one module, one command, and one test share.

The Django Way

Step 1: Check the starting point

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

OK
git status --short
git log --oneline -1
... Warn about unsafe settings at startup

Step 2: Where Django finds commands

Django looks for commands in each installed app’s management/commands/ folder; each module there is a command named after the file. Both folders need an __init__.py, which may be empty. Create them in the three apps that will hold this chapter’s commands:

accounts/management/__init__.py
accounts/management/commands/__init__.py
events/management/__init__.py
events/management/commands/__init__.py
registrations/management/__init__.py
registrations/management/commands/__init__.py

A command lives in the app that owns its data: groups and roles in accounts, sample events in events, places in registrations.

Step 3: ensure_groups, from one list

Chapter 30’s migration created the groups from a list inside the migration file, and Chapter 30’s test kept its own copy, which Chapter 38 had to change too. A third copy in a command would make three. Move the list to one module, accounts/roles.py:

"""The groups Otahque expects, with their permissions.

Chapter 41: one list, read by the ensure_groups command
and by the tests. The migration that first made the
groups (accounts/migrations/0004_groups.py) keeps its own
copy, because a migration must not import application
code: it describes the database as it was then.
"""
GROUPS = {
    'Organizers': [
        'events.add_event', 'events.change_event',
    ],
    'Administrators': [
        'accounts.change_user', 'accounts.view_user',
        'admin.view_logentry', 'audit.view_auditevent',
        'events.change_event',
        'events.add_organizerassignment',
        'events.change_organizerassignment',
        'events.view_organizerassignment',
        'events.delete_event', 'events.manage_organizers',
        'events.view_event',
        'registrations.view_registration',
        'registrations.view_registrationquestion',
    ],
}

The migrations keep their own copies on purpose: a migration describes the database as it was when it was written, and must not change because application code did. Chapter 30’s test now reads the shared list. In accounts/tests/test_accounts.py, delete the block that starts:

# Chapter 30: the two groups the migration creates.
GROUPS = {

up to class GroupTests, and add from accounts.roles import GROUPS below the other accounts imports. Then the command’s tests, in a new file accounts/tests/test_groups.py:

"""ensure_groups reports and repairs the groups (Chapter 41)."""
import io

from django.contrib.auth.models import Group, Permission
from django.core.management import call_command
from django.core.management.base import CommandError
from django.test import TestCase


def run(*args):
    """Run ensure_groups; return what it printed."""
    out = io.StringIO()
    call_command('ensure_groups', *args, stdout=out)
    return out.getvalue()


class EnsureGroupsTests(TestCase):
    """The groups match accounts/roles.py, or are made to."""

    def test_the_migrated_groups_match(self):
        self.assertIn('Both groups match', run('--check'))

    def test_a_changed_group_is_reported_then_fixed(self):
        admins = Group.objects.get(name='Administrators')
        admins.permissions.remove(Permission.objects.get(
            codename='view_registration'))
        admins.permissions.add(Permission.objects.get(
            codename='delete_user'))
        with self.assertRaisesMessage(CommandError,
                                      '2 difference(s)'):
            run('--check')
        out = run()
        self.assertIn('Administrators: missing '
                      'registrations.view_registration', out)
        self.assertIn('Administrators: extra '
                      'accounts.delete_user', out)
        self.assertIn('Both groups match', run('--check'))

    def test_a_missing_group_is_made(self):
        Group.objects.filter(name='Organizers').delete()
        self.assertIn('Organizers: no such group', run())
        self.assertIn('Both groups match', run('--check'))

    def test_running_twice_changes_nothing(self):
        run()
        self.assertIn('Both groups match', run())
uv run python manage.py test accounts.tests.test_groups
Found 4 test(s).
Creating test database for alias 'default'...
ERROR: test_a_missing_group_is_made
django.core.management.base.CommandError: Unknown command:
    'ensure_groups'
ERROR: test_running_twice_changes_nothing
django.core.management.base.CommandError: Unknown command:
    'ensure_groups'
... (2 more like these)
Ran 4 tests in ...s

FAILED (failures=1, errors=3)

The command, in accounts/management/commands/ensure_groups.py:

"""Create Otahque's groups, or put back their permissions.

Chapter 41. Usage:
    uv run python manage.py ensure_groups --check
    uv run python manage.py ensure_groups
"""
from django.contrib.auth.models import Group, Permission
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction

from accounts.roles import GROUPS


def name_of(permission):
    """Return a permission's name, such as events.add_event."""
    app_label = permission.content_type.app_label
    return f'{app_label}.{permission.codename}'


def permission(name):
    """Return the permission named like events.add_event."""
    app_label, codename = name.split('.')
    return Permission.objects.get(
        content_type__app_label=app_label, codename=codename,
    )


class Command(BaseCommand):
    """Compare each group with accounts/roles.py; fix it."""

    help = ("Create Otahque's groups, or put back their "
            'permissions; --check only reports.')

    def add_arguments(self, parser):
        """Add --check, which changes nothing."""
        parser.add_argument(
            '--check', action='store_true',
            help='Report differences; change nothing.',
        )

    def handle(self, *args, check=False, **options):
        """Report each difference, then fix it unless --check."""
        found = 0
        with transaction.atomic():
            for group_name, names in GROUPS.items():
                wanted = {permission(name) for name in names}
                group = Group.objects.filter(
                    name=group_name
                ).first()
                held = set(group.permissions.all()
                           if group else [])
                lines = ([f'{group_name}: no such group']
                         if group is None else [])
                lines += [f'{group_name}: missing {name_of(p)}'
                          for p in wanted - held]
                lines += [f'{group_name}: extra {name_of(p)}'
                          for p in held - wanted]
                for line in sorted(lines):
                    self.stdout.write(line)
                found += len(lines)
                if lines and not check:
                    group = group or Group.objects.create(
                        name=group_name
                    )
                    group.permissions.set(wanted)
        if not found:
            self.stdout.write('Both groups match roles.py.')
        elif check:
            raise CommandError(
                f'{found} difference(s); run without --check '
                'to fix them.'
            )
        else:
            self.stdout.write(f'Fixed {found} difference(s).')

--check only reports, and exits with 1 when anything differs, so a release script can stop on it; without --check the command sets each group to exactly the list. Everything happens in one transaction, so a failure leaves both groups as they were.

uv run python manage.py test accounts.tests.test_groups
uv run python manage.py ensure_groups --check
Found 4 test(s).
Creating test database for alias 'default'...
...
Ran 4 tests in ...s

OK
Both groups match roles.py.

Your own database matches too, including the permission Chapter 38 added.

Step 4: seed_demo, the same community everywhere

The tests first, in events/tests/test_seed.py. seeded() runs the command inside a transaction it rolls back, so one test can run it twice and compare:

"""seed_demo makes the same community each time (Chapter 41)."""
import io

from django.core.management import call_command
from django.core.management.base import CommandError
from django.db import transaction
from django.test import TestCase

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


def seeded(seed=41):
    """Seed in a transaction, describe what was made, undo it."""
    with transaction.atomic():
        call_command('seed_demo', seed=seed,
                     stdout=io.StringIO())
        made = (
            sorted(User.objects.values_list('email', flat=True)),
            sorted(Event.objects.values_list('title',
                                             'capacity')),
            sorted(Registration.objects.values_list(
                'event__title', 'member__email')),
        )
        transaction.set_rollback(True)
    return made


class SeedDemoTests(TestCase):
    """Small by default; deterministic; never twice."""

    def test_the_same_data_twice(self):
        first, second = seeded(), seeded()
        self.assertEqual(first, second)
        members, events, places = first
        self.assertEqual((len(members), len(events)), (20, 6))
        self.assertTrue(places)

    def test_another_seed_gives_other_places(self):
        self.assertNotEqual(seeded(41)[2], seeded(7)[2])

    def test_it_refuses_to_run_twice(self):
        call_command('seed_demo', stdout=io.StringIO())
        with self.assertRaisesMessage(CommandError,
                                      'Demo data exists'):
            call_command('seed_demo', stdout=io.StringIO())

    def test_demo_members_cannot_sign_in(self):
        call_command('seed_demo', stdout=io.StringIO())
        member = User.objects.filter(
            email__endswith='@demo.otahque.example').first()
        self.assertFalse(member.has_usable_password())

The command, in events/management/commands/seed_demo.py:

"""Make the same sample community on every reader's machine.

Chapter 41. Usage:
    uv run python manage.py seed_demo
    uv run python manage.py seed_demo --size large

Every name comes from fixed lists, and every choice from
random.Random(seed), so two runs with the same seed make
the same members, events, and places. Demo members have
addresses at demo.otahque.example and no password: they
cannot sign in.
"""
import random
from datetime import timedelta

from allauth.account.models import EmailAddress
from django.contrib.auth.models import Group
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from django.utils import timezone

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

DOMAIN = 'demo.otahque.example'
NAMES = ['Aarav', 'Bea', 'Chen', 'Dara', 'Elif', 'Farah',
         'Gus', 'Hana', 'Ines', 'Jomo', 'Kai', 'Lena', 'Mo',
         'Nia', 'Omar', 'Pia', 'Quinn', 'Ravi', 'Sofia', 'Tom']
TOPICS = ['Python clinic', 'Django evening', 'Testing workshop',
          'Data meetup', 'Beginners night', 'Code review circle']
PLACES = [('Leeds Central Library', 'Europe/London'),
          ('Manchester Hub', 'Europe/London'),
          ('Pune Tech Park', 'Asia/Kolkata'),
          ('Online', 'UTC')]
# Members, events, and organizers for each size.
SIZES = {'small': (20, 6, 2), 'large': (1000, 120, 10)}


def demo_member(number, name):
    """Create one demo member with a confirmed address."""
    email = f'{name.lower()}.{number}@{DOMAIN}'
    member = User.objects.create_user(
        email, display_name=f'{name} {number}'
    )
    EmailAddress.objects.create(user=member, email=email,
                                verified=True, primary=True)
    return member


class Command(BaseCommand):
    """Create demo members, events, and places, or refuse."""

    help = 'Create the sample community used in later chapters.'

    def add_arguments(self, parser):
        """Add --size and --seed."""
        parser.add_argument('--size', choices=SIZES,
                            default='small')
        parser.add_argument('--seed', type=int, default=41)

    def handle(self, *args, size='small', seed=41, **options):
        """Refuse if demo data exists; otherwise make it."""
        if User.objects.filter(
                email__endswith=f'@{DOMAIN}').exists():
            raise CommandError('Demo data exists already.')
        members_wanted, events_wanted, organizers = SIZES[size]
        chance = random.Random(seed)
        today = timezone.now().replace(hour=18, minute=0,
                                       second=0, microsecond=0)
        with transaction.atomic():
            members = [demo_member(n, NAMES[n % len(NAMES)])
                       for n in range(1, members_wanted + 1)]
            group = Group.objects.get(name='Organizers')
            for member in members[:organizers]:
                member.groups.add(group)
            places = 0
            for n in range(events_wanted):
                location, zone = PLACES[n % len(PLACES)]
                starts = today + timedelta(
                    days=chance.randint(-60, 60))
                event = Event.objects.create(
                    title=f'{TOPICS[n % len(TOPICS)]} {n + 1}',
                    starts_at=starts,
                    ends_at=starts + timedelta(hours=2),
                    timezone=zone, location=location,
                    capacity=chance.choice([10, 20, 40]),
                    status=Event.Status.PUBLISHED,
                    registration_closes_at=starts,
                    cancellation_deadline=starts,
                )
                event.add_organizer(members[n % organizers])
                taken = chance.sample(
                    members[organizers:],
                    k=min(event.capacity - 2,
                          members_wanted - organizers),
                )
                event.registrations.bulk_create([
                    event.registrations.model(
                        event=event, member=member,
                        registered_at=starts - timedelta(
                            days=chance.randint(2, 20)),
                    )
                    for member in taken
                ])
                places += len(taken)
        self.stdout.write(
            f'Made {len(members)} members, {events_wanted} '
            f'events, and {places} places (seed {seed}).'
        )

Two choices make it deterministic. Every name comes from fixed lists, and every random choice from random.Random(seed), a generator of its own: the same seed gives the same sequence on every machine, and Otahque’s code never touches Python’s shared generator. The places are made with bulk_create(), not register(): sample data does not need the lock, and the counts are kept below capacity by construction. Readers who need a larger community later, for the search and load chapters, run seed_demo --size large.

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

OK
Made 20 members, 6 events, and 78 places (seed 41).

Your database now holds the demo community beside your own data. Its members have addresses at demo.otahque.example and no password, so nobody can sign in as them.

Common Error: random.seed() in a command

Calling random.seed(41) and then random.choice() seems to give the same result, until some other code, a library or a test, uses the shared generator in between, and the sequence shifts. random.Random(41) is a generator nobody else can touch.

Step 5: A fixture round trip

A test proves the demo data survives a trip through a fixture with natural keys, in config/tests/test_fixtures.py:

"""Fixtures with natural keys: dump, empty, load (Chapter 41)."""
import io
import tempfile
from pathlib import Path

from django.core.management import call_command
from django.test import TransactionTestCase

from accounts.models import Profile, User
from events.models import Event, OrganizerAssignment
from registrations.models import Registration

# Left out: secrets (mfa), sessions, the admin's log, and
# the rows Django and migrations make for themselves.
EXCLUDE = ['mfa', 'sessions', 'admin.logentry', 'contenttypes',
           'auth.permission', 'auth.group']
MODELS = [User, Profile, Event, OrganizerAssignment,
          Registration]


def counts():
    """Count the rows of the models a fixture carries."""
    return {model.__name__: model.objects.count()
            for model in MODELS}


class FixtureRoundTripTests(TransactionTestCase):
    """seed_demo, dumpdata, flush, ensure_groups, loaddata."""

    # Put back what migrations made (the groups) afterwards.
    serialized_rollback = True

    def test_a_round_trip_keeps_every_row(self):
        call_command('seed_demo', stdout=io.StringIO())
        before = counts()
        dumped = io.StringIO()
        call_command('dumpdata', '--natural-foreign',
                     '--natural-primary', '--indent', '1',
                     *[f'--exclude={name}' for name in EXCLUDE],
                     stdout=dumped)
        self.assertNotIn('"model": "mfa.', dumped.getvalue())
        call_command('flush', '--no-input', verbosity=0)
        self.assertEqual(User.objects.count(), 0)
        call_command('ensure_groups', stdout=io.StringIO())
        with tempfile.TemporaryDirectory() as folder:
            fixture = Path(folder) / 'demo.json'
            fixture.write_text(dumped.getvalue(),
                               encoding='utf-8')
            call_command('loaddata', fixture, verbosity=0)
        self.assertEqual(counts(), before)
        self.assertTrue(User.objects.filter(
            groups__name='Organizers').exists())
uv run python manage.py test config.tests.test_fixtures
Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...s

OK

Read it as a story. dumpdata writes members as their email and groups as their names, so nothing depends on id numbers. flush empties every table, including the groups that Chapter 30’s migration made, which migrations will not make again. ensure_groups puts them back, and loaddata then finds the Organizers group by name for the two demo organizers. The test is a TransactionTestCase because flush must really empty the tables; serialized_rollback puts the migrated rows back afterwards for the tests that follow.

Common Error: loading a fixture without natural keys

A fixture dumped with plain ids says “this member is in group 2” and “this permission is number 37”. Loaded into another database, group 2 may be Administrators, and permission 37 may be something else entirely: no error, just wrong rows. Use --natural-foreign --natural-primary, and exclude what Django and migrations make for themselves (contenttypes, auth.permission).

Step 6: Where a place came from

In registrations/models.py, inside Registration, below Status:

    class Source(models.TextChoices):
        """How the place was made (Chapter 41)."""

        SITE = 'site', 'On the site'
        IMPORT = 'import', 'Imported by an operator'

and below answers:

    source = models.CharField(
        max_length=10,
        choices=Source,
        default=Source.SITE,
    )
uv run python manage.py makemigrations -n source registrations
uv run python manage.py migrate
Migrations for 'registrations':
  registrations\migrations\0006_source.py
    + Add field source to registration
Operations to perform:
  Apply all migrations: account, accounts, admin, audit,
    auth, contenttypes, events, mfa, registrations, sessions,
    socialaccount
Running migrations:
  Applying registrations.0006_source... OK

The default fills every existing place with site, which is true: until now, every place was taken on the site.

Step 7: register() for an import

The import must run every rule but the window. In events/models.py, below FACTS:

# The refusals an import ignores (Chapter 41, D41.3).
WINDOW = ('not_open', 'closed')

and register() becomes:

    def register(self, member, now, answers=None,
                 source='site'):
        """Give member a place, or raise ValidationError.

        The event row is locked first, so requests for it
        take turns, and every check reads the locked row,
        not this copy, which may be out of date. The unique
        rule is still the backstop for the same member.
        The answers are saved with the place, or neither is.
        An import (source='import', Chapter 41) ignores the
        registration window; every other rule holds.
        """
        with transaction.atomic():
            event = self.locked()
            problems = event.registration_problems(
                member, now, answers
            )
            if source == 'import':
                problems = [code for code in problems
                            if code not in WINDOW]
            if problems:
                raise refusal(problems)
            try:
                with transaction.atomic():
                    return event.registrations.create(
                        member=member, registered_at=now,
                        answers=answers or {}, source=source,
                    )
            except IntegrityError:
                # Only the one-active-place rule means a
                # repeat; any other failure is re-raised.
                if event.place_of(member) is None:
                    raise
            raise refusal(['already_registered'])

The window codes are removed from the list after it is built, so a new rule added to registration_problems() later applies to imports too, without anyone remembering to.

Step 8: import_registrations

The tests, in registrations/tests/test_import.py. One file covers every kind of row: two members to import, an unknown email, a member who has not confirmed their email, and a repeat:

"""import_registrations: places from a file (Chapter 41)."""
import io
import tempfile
from pathlib import Path

from django.core.management import call_command
from django.core.management.base import CommandError
from django.test import TestCase
from django.utils import timezone

from accounts.models import User
from registrations.models import Registration
from registrations.models import RegistrationQuestion as Question

from .test_registrations import soon, verified


def run(event, text, *args, encoding='utf-8'):
    """Import text as a CSV file; return what was printed."""
    out = io.StringIO()
    with tempfile.TemporaryDirectory() as folder:
        path = Path(folder) / 'people.csv'
        path.write_text(text, encoding=encoding)
        try:
            call_command('import_registrations', event.pk, path,
                         *args, stdout=out)
        except CommandError as error:
            out.write(f'CommandError: {error}\n')
    return out.getvalue()


ROWS = ('Name,Email\n'
        'Sai,sai@example.org\n'
        'Raj,RAJ@example.org\n'
        'Nobody,nobody@example.org\n'
        'Una,una@example.org\n'
        'Sai again,sai@example.org\n')


class ImportTests(TestCase):
    """Each row gets a reason; nothing is invented."""

    def setUp(self):
        self.event = soon(capacity=3)
        verified('sai@example.org')
        verified('raj@example.org')
        User.objects.create_user('una@example.org',
                                 display_name='Una')

    def test_each_row_gets_its_reason(self):
        out = run(self.event, ROWS)
        self.assertIn('row 2: sai@example.org: imported', out)
        self.assertIn('row 3: raj@example.org: imported', out)
        self.assertIn('row 4: nobody@example.org: refused: '
                      'no member has this email', out)
        self.assertIn('row 5: una@example.org: refused: '
                      'unverified', out)
        self.assertIn('row 6: sai@example.org: skipped', out)
        self.assertIn('Imported 2, skipped 1, refused 2.', out)
        self.assertIn('CommandError: 2 row(s) refused', out)
        self.assertFalse(User.objects.filter(
            email='nobody@example.org').exists())

    def test_a_dry_run_saves_nothing(self):
        out = run(self.event, ROWS, '--dry-run')
        self.assertIn('Would import 2', out)
        self.assertIn('Dry run: nothing saved.', out)
        self.assertEqual(Registration.objects.count(), 0)

    def test_imported_places_are_marked(self):
        run(self.event, ROWS)
        self.assertEqual(
            set(Registration.objects.values_list('source',
                                                 flat=True)),
            {Registration.Source.IMPORT},
        )

    def test_a_rerun_imports_nothing_new(self):
        run(self.event, ROWS)
        out = run(self.event, ROWS)
        self.assertIn('Imported 0, skipped 3, refused 2.', out)
        self.assertEqual(Registration.objects.count(), 2)

    def test_capacity_holds_and_the_window_does_not(self):
        closed = soon(capacity=1,
                      registration_closes_at=timezone.now())
        out = run(closed, ROWS)
        self.assertIn('row 2: sai@example.org: imported', out)
        self.assertIn('row 3: raj@example.org: refused: full',
                      out)

    def test_an_event_that_asks_questions(self):
        Question.objects.create(event=self.event, label='Level',
                                kind=Question.Kind.SHORT)
        out = run(self.event, 'email\nsai@example.org\n')
        self.assertIn('imported', out)
        Question.objects.create(event=self.event,
                                label='Laptop?',
                                kind=Question.Kind.YES_NO,
                                required=True)
        out = run(self.event, 'email\nraj@example.org\n')
        self.assertIn('refused: answers_needed', out)

    def test_a_file_from_excel_with_a_bom(self):
        out = run(self.event, 'Email\nsai@example.org\n',
                  encoding='utf-8-sig')
        self.assertIn('Imported 1', out)

    def test_a_file_without_an_email_column(self):
        out = run(self.event, 'Name\nSai\n')
        self.assertIn('CommandError: The file has no email '
                      'column.', out)

The command, in registrations/management/commands/import_registrations.py:

"""Give existing members places in an event, from a CSV file.

Chapter 41. Usage:
    uv run python manage.py import_registrations 7 people.csv
    ... --dry-run    to see each row's outcome, saving nothing

The file needs an email column; other columns are read
but not used. Each address must belong to a member with
a confirmed email: no account is ever created. Every
rule of Event.register() holds except the registration
window, and each place made is marked source=import.
"""
import csv
from pathlib import Path

from django.core.exceptions import ValidationError
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from django.utils import timezone

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

MAX_BYTES = 1_000_000
MAX_ROWS = 2_000


def read_rows(path):
    """Return the file's rows as dictionaries, or refuse.

    utf-8-sig reads files with or without the BOM that
    Excel writes at the start.
    """
    if not path.is_file():
        raise CommandError(f'No such file: {path}')
    if path.stat().st_size > MAX_BYTES:
        raise CommandError('The file is larger than 1 MB.')
    try:
        with path.open(encoding='utf-8-sig', newline='') as f:
            reader = csv.DictReader(f)
            fields = [n.strip().lower()
                      for n in reader.fieldnames or []]
            if 'email' not in fields:
                raise CommandError('The file has no email '
                                   'column.')
            reader.fieldnames = fields
            rows = list(reader)
    except UnicodeDecodeError:
        raise CommandError('Save the file as UTF-8.') from None
    if len(rows) > MAX_ROWS:
        raise CommandError(f'More than {MAX_ROWS} rows.')
    return rows


class Command(BaseCommand):
    """Import places row by row, and report each outcome."""

    help = 'Give existing members places in an event.'

    def add_arguments(self, parser):
        """Add the event, the file, and --dry-run."""
        parser.add_argument('event_id', type=int)
        parser.add_argument('csv_file', type=Path)
        parser.add_argument(
            '--dry-run', action='store_true',
            help="Show each row's outcome; save nothing.",
        )

    def handle(self, event_id, csv_file, dry_run=False,
               **options):
        """Run every row in one transaction; report; exit."""
        event = Event.objects.filter(pk=event_id).first()
        if event is None:
            raise CommandError(f'No event with id {event_id}.')
        rows = read_rows(csv_file)
        totals = {'imported': 0, 'skipped': 0, 'refused': 0}
        with transaction.atomic():
            for number, row in enumerate(rows, start=2):
                email = (row.get('email') or '').strip().lower()
                outcome, reason = self.place(event, email)
                totals[outcome] += 1
                self.stdout.write(
                    f'row {number}: {email or "(empty)"}: '
                    f'{outcome}{reason}'
                )
            if dry_run:
                # Every row ran for real, under the same
                # locks; now undo all of it.
                transaction.set_rollback(True)
        verb = 'Would import' if dry_run else 'Imported'
        self.stdout.write(
            f"{verb} {totals['imported']}, skipped "
            f"{totals['skipped']}, refused {totals['refused']}."
            + (' Dry run: nothing saved.' if dry_run else '')
        )
        if totals['refused']:
            raise CommandError(
                f"{totals['refused']} row(s) refused; see above."
            )

    def place(self, event, email):
        """Try one row; return its outcome and a reason."""
        member = User.objects.filter(email=email).first()
        if member is None:
            return 'refused', ': no member has this email'
        try:
            event.register(member, timezone.now(), answers={},
                           source='import')
        except ValidationError as error:
            codes = [e.code for e in error.error_list]
            if codes == ['already_registered']:
                return 'skipped', ': already has a place'
            return 'refused', ': ' + ', '.join(codes)
        return 'imported', ''

Each row takes the path in Figure 41.2.

Inside a box labelled One transaction, five numbered cards joined by arrows. 1, read the file: UTF-8, with or without a BOM; an email column; at most 2,000 rows and 1 MB. 2, find the member: by email; no member, refused, no account made. 3, Event.register with source import: the same lock and rules; the window ignored, capacity kept. 4, report the row: imported, skipped (already has a place), or refused, with the reason. 5, dry run: roll everything back; the preview ran the real checks; nothing saved.
Figure 41.2 — An import, row by row, in one transaction.

answers={} matters (N41.7). None would mean “not asked yet”, and an event with any question would refuse every row; an empty answer set means “asked, nothing given”, so an event with only optional questions imports, and one with a required question or a profile fact refuses the row with answers_needed: that member registers on the site instead. A repeat is “skipped”, not refused, so running the same file twice is safe and exits with 0.

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

OK

Common Error: a file saved by Excel

Excel’s “CSV UTF-8” starts the file with a byte order mark. Read with encoding='utf-8', the first heading becomes Email, the email column is “missing”, and every row fails. utf-8-sig reads the mark if it is there and is harmless if it is not; test_a_file_from_excel_with_a_bom keeps it that way.

Step 9: The runbook

An operator will run this command months from now, without this chapter open. Create docs/runbooks/import.md:

# Runbook: importing places from a spreadsheet

Status: Drafted in Chapter 41, for review. Not approved.
Command: import_registrations. Decisions: D41.1-D41.3,
N41.7 (DECISIONS.md).

## Before

1. Ask the organizer for a CSV file, saved as UTF-8,
   with an email column. Other columns are ignored.
2. Find the event's id: the number in its address,
   /events/<id>/.
3. Check that the file holds only the people who agreed
   to have a place. An import is not proof of consent.

## Run

    uv run python manage.py import_registrations <id> \
        people.csv --dry-run

Read each row's outcome. Then run it again without
--dry-run. The real run repeats every check.

## Outcomes

| Outcome                     | Meaning and action        |
|-----------------------------|---------------------------|
| imported                    | A place, source=import    |
| skipped: already has a place| Nothing to do             |
| refused: no member has...   | Ask them to sign up first |
| refused: unverified         | They confirm their email  |
| refused: full               | Capacity reached          |
| refused: answers_needed     | They register on the site |
| refused: not_published      | Publish the event first   |

The registration window is ignored; capacity is not.
The command exits with an error when any row is refused,
after saving the rows that were imported. A second run
of the same file imports nothing new.

## After

Delete the file. It holds people's email addresses.

Step 10: The attendee download

First record the new action. In audit/models.py, at the end of Action:

        DOWNLOAD_ATTENDEES = (
            'download_attendees', 'Download an attendee list'
        )
uv run python manage.py makemigrations -n download_action audit
uv run python manage.py migrate
Migrations for 'audit':
  audit\migrations\0004_download_action.py
    ~ Alter field action on auditevent
Operations to perform:
  Apply all migrations: account, accounts, admin, audit,
    auth, contenttypes, events, mfa, registrations, sessions,
    socialaccount
Running migrations:
  Applying audit.0004_download_action... OK

The tests, in registrations/tests/test_download.py. Sai’s display name is a formula, her answer starts with a minus, her company holds an ø, and her phone has a plus; the method table at the end pins the download to the same answers as the list:

"""The attendee download: who, what, and how (Chapter 41)."""
from django.test import TestCase
from django.utils import timezone

from accounts.models import Profile
from audit.models import AuditEvent
from config.helpers import answers, in_group
from events.models import Event
from events.tests.test_methods import SIGNED_OUT_FIRST
from registrations.models import RegistrationQuestion as Question

from .test_registrations import soon, url, verified

Action = AuditEvent.Action


def text_of(response):
    """Return a streamed download as one string."""
    return b''.join(response.streaming_content).decode()


class DownloadTests(TestCase):
    """The organizer's CSV, its cells, and its record."""

    @classmethod
    def setUpTestData(cls):
        cls.event = soon(asks_company=True)
        cls.sam = in_group('sam@example.org', 'Organizers')
        cls.event.add_organizer(cls.sam)
        level = Question.objects.create(
            event=cls.event, label='Python level',
            kind=Question.Kind.SHORT)
        sai = verified('sai@example.org')
        sai.display_name = '=HYPERLINK("http://x.example")'
        sai.save()
        profile = Profile.of(sai)
        profile.phone = '+447700900123'
        profile.company = 'Søren & Co'
        profile.save()
        cls.event.register(sai, timezone.now(),
                           answers={level.key: '-1 beginner'})

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

    def download(self):
        """Download the event's CSV as Sam."""
        return self.client.get(url('download', self.event.pk))

    def test_a_named_csv_file(self):
        response = self.download()
        self.assertEqual(response['Content-Type'],
                         'text/csv; charset=utf-8')
        name = f'attendees-{self.event.pk}.csv'
        self.assertEqual(response['Content-Disposition'],
                         f'attachment; filename="{name}"')

    def test_the_columns_and_the_bom(self):
        header = text_of(self.download()).splitlines()[0]
        self.assertTrue(header.startswith('\ufeffName,Email,'))
        self.assertTrue(header.endswith(',Company,Python level'))

    def test_typed_text_cannot_run_as_a_formula(self):
        row = text_of(self.download()).splitlines()[1]
        quoted = '"\'=HYPERLINK(""http://x.example"")"'
        self.assertTrue(row.startswith(quoted))
        self.assertIn(",'-1 beginner", row)
        self.assertIn('Søren & Co', row)

    def test_the_phone_is_spaced_and_not_guarded(self):
        row = text_of(self.download()).splitlines()[1]
        self.assertIn(',+44 7700 900123,', row)

    def test_each_download_is_recorded(self):
        text_of(self.download())
        record = AuditEvent.objects.get(
            action=Action.DOWNLOAD_ATTENDEES)
        self.assertEqual(record.actor, self.sam)
        self.assertEqual(record.detail, {'rows': 1})

    def test_head_records_nothing(self):
        self.client.head(url('download', self.event.pk))
        self.assertFalse(AuditEvent.objects.filter(
            action=Action.DOWNLOAD_ATTENDEES).exists())

    def test_the_administrator_may_download(self):
        soni = in_group('soni@example.org', 'Administrators')
        self.client.force_login(soni)
        self.assertEqual(self.download().status_code, 200)


# The download answers as the attendee list does: sign-in
# first; GET and HEAD for the event's organizers and the
# administrator; 403, recorded, for any other member.
ALLOW = 'GET, HEAD, OPTIONS'
DOWNLOAD_OTHER = [
    (method, 'sign in',
     '403 recorded' if method in ('GET', 'HEAD')
     else f'ok {ALLOW}' if method == 'OPTIONS'
     else f'405 {ALLOW}')
    for method, _, _ in SIGNED_OUT_FIRST
]


class DownloadMethodTests(TestCase):
    """The download's answer to each method, pinned."""

    @classmethod
    def setUpTestData(cls):
        cls.event = soon()
        cls.sam = in_group('sam@example.org', 'Organizers')
        cls.event.add_organizer(cls.sam)
        cls.sai = verified('sai@example.org')
        cls.draft = soon(status=Event.Status.DRAFT)

    def check(self, member, table, event=None):
        """Compare the download's answers with each row."""
        path = url('download', (event or self.event).pk)
        for method, signed_out, signed_in in table:
            with self.subTest(method):
                self.assertEqual(
                    answers(path, member, method),
                    (signed_out, signed_in),
                )

    def test_for_an_organizer(self):
        self.check(self.sam, SIGNED_OUT_FIRST)

    def test_for_anyone_else(self):
        self.check(self.sai, DOWNLOAD_OTHER)

    def test_a_hidden_draft(self):
        self.check(self.sai,
                   [('GET', 'sign in', '404 recorded')],
                   self.draft)
uv run python manage.py test registrations.tests.test_download
Found 10 test(s).
Creating test database for alias 'default'...
ERROR: test_a_hidden_draft
django.urls.exceptions.NoReverseMatch: Reverse for 'download'
    not found. 'download' is not a valid view function or
    pattern name.
ERROR: test_a_named_csv_file
django.urls.exceptions.NoReverseMatch: Reverse for 'download'
    not found. 'download' is not a valid view function or
    pattern name.
... (8 more like these)
Ran 10 tests in ...s

FAILED (errors=10)

The columns, in a new file registrations/table.py, used by both the page and the file:

"""The attendee table, for the page and the download.

Chapter 41: one place decides the columns, so the list
Sam reads and the file he downloads never disagree.
"""
import csv
from zoneinfo import ZoneInfo

from django.utils import timezone

from events.models import fact_of

# A cell starting with one of these may run as a formula
# in a spreadsheet (OWASP, CSV injection).
FORMULA = ('=', '+', '-', '@', '\t', '\r')


def shown(value):
    """Return one answer as the attendee list shows it."""
    if isinstance(value, list):
        return ', '.join(value)
    if isinstance(value, dict):
        return 'Agreed'
    return '' if value is None else str(value)


def columns(event):
    """Return the facts and questions the table shows."""
    return event.asked_facts(), list(event.questions.all())


def extra_cells(place, facts, questions):
    """Return a place's fact cells and answer cells."""
    return ([fact_of(place.member, name) for name in facts],
            [shown(place.answers.get(question.key))
             for question in questions])


def headings(event, facts, questions):
    """Return the download's header row."""
    return (['Name', 'Email', 'Phone',
             f'Registered ({event.timezone})']
            + [name.capitalize() for name in facts]
            + [question.label + (' (removed)'
                                 if question.archived else '')
               for question in questions])


def guarded(text):
    """Return text that a spreadsheet shows, never runs.

    The leading apostrophe makes Excel and LibreOffice
    read the cell as text.
    """
    text = str(text)
    return "'" + text if text.startswith(FORMULA) else text


def phone_cell(member):
    """Return the phone number as +44 7700 900123, or ''.

    Written by Otahque from a checked number, so it is not
    guarded: spaced like this, spreadsheets keep it text.
    """
    profile = getattr(member, 'profile', None)
    phone = profile.phone if profile else None
    return phone.as_international if phone else ''


class Echo:
    """A file whose write() hands back what it was given."""

    def write(self, value):
        """Return value, so csv.writer yields each line."""
        return value


def csv_lines(event, places):
    """Yield the download, line by line, starting with a BOM.

    The byte order mark tells Excel the file is UTF-8, so
    names such as Søren arrive intact.
    """
    facts, questions = columns(event)
    zone = ZoneInfo(event.timezone)
    writer = csv.writer(Echo())
    yield '\ufeff'
    yield writer.writerow(
        [guarded(cell)
         for cell in headings(event, facts, questions)])
    for place in places:
        member = place.member
        registered = timezone.localtime(place.registered_at,
                                        zone)
        fact_values, answers = extra_cells(place, facts,
                                           questions)
        yield writer.writerow(
            [guarded(member.display_name),
             guarded(member.email),
             phone_cell(member),
             f'{registered:%Y-%m-%d %H:%M}']
            + [guarded(value) for value in fact_values]
            + [guarded(value) for value in answers])

shown() moves here from the views. In registrations/views.py, the imports from audit.models to .models become:

from audit.models import AuditEvent, record
from events.models import REASONS, Event
from events.views import deny, page_numbers

from .forms import DetailsForm, MyPlacesForm
from .models import Registration
from .table import columns, csv_lines, extra_cells

with from django.http import StreamingHttpResponse added above the django.shortcuts import. Then everything from def shown(value): to the end of the file becomes:

def attendees_of(request, event_id, action):
    """Return the event, if this member may see its list.

    The page and the download refuse the same people, each
    refusal recorded as an attempt at action.
    """
    event = get_object_or_404(Event, pk=event_id)
    if not event.is_visible_to(request.user):
        deny(request, action, event, hidden=True)
    if not event.can_see_attendees(request.user):
        deny(request, action, event)
    return event


class AttendeesView(ListView):
    """The attendee list, for the event's organizers.

    One column per profile fact the event asks for, and
    one per question; archived questions keep their column.
    """

    template_name = 'registrations/attendees.html'
    context_object_name = 'places'

    def get(self, request, *args, **kwargs):
        """Refuse anyone who may not see the list."""
        self.event = attendees_of(request, kwargs['event_id'],
                                  Action.VIEW_ATTENDEES)
        return super().get(request, *args, **kwargs)

    def get_queryset(self):
        """Places held now, with each member and profile."""
        return self.event.registrations.active().with_people()

    def get_context_data(self, **kwargs):
        """Add the columns and a row of answers per place."""
        context = super().get_context_data(**kwargs)
        facts, questions = columns(self.event)
        rows = [(place, *extra_cells(place, facts, questions))
                for place in context['places']]
        return context | {
            'event': self.event,
            'facts': facts,
            'questions': questions,
            'rows': rows,
            'counts': self.event.registrations
            .cancellation_counts(),
        }


class AttendeesDownloadView(View):
    """The attendee table as a CSV file (Chapter 41).

    The same people as the page may download it; each
    download is recorded, with how many rows it held.
    """

    def get(self, request, event_id):
        """Record the download, then stream the file."""
        event = attendees_of(request, event_id,
                             Action.DOWNLOAD_ATTENDEES)
        places = event.registrations.active().with_people()
        if request.method == 'GET':
            record(request.user, Action.DOWNLOAD_ATTENDEES,
                   event, rows=places.count())
        response = StreamingHttpResponse(
            csv_lines(event, places),
            content_type='text/csv; charset=utf-8',
        )
        response['Content-Disposition'] = (
            f'attachment; filename="attendees-{event.pk}.csv"'
        )
        return response

attendees_of() is the refusal both views share. Only a GET records a download: a HEAD request sends the headers without the file. In registrations/urls.py, below the attendee list’s path:

    path('events/<int:event_id>/registrations/download/',
         views.AttendeesDownloadView.as_view(),
         name='download'),
uv run python manage.py test registrations.tests.test_download
Found 10 test(s).
Creating test database for alias 'default'...
...
Ran 10 tests in ...s

OK

Now the page. In registrations/templates/registrations/attendees.html, the paragraph “Contact details are for running this event only...” is replaced by the action bar and the notice, inside {% if places %} and above the table’s card:

    {# Chapter 41: the download, and what it holds. #}
    <div class="table-actions">
      <a href="{% url 'registrations:download' event.pk %}"
         class="btn btn-primary">Download CSV</a>
      <span>{{ places|length }} row{{ places|length|pluralize }},
        with the columns below</span>
    </div>
    <aside class="notice-card" aria-label="Personal data">
      <p><strong>This list holds personal data.</strong>
        Names, email addresses, phone numbers, and answers
        are for running this event only. Every download is
        recorded. Delete the file when the event is over.</p>
    </aside>

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

  /* The attendee download (Chapter 41): an action bar
     above the table, and a notice about personal data. */
  .table-actions {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 0.75rem 1rem;
  }
  .notice-card {
    padding: 0.75rem 1rem;
    border: 1px solid var(--color-base-300);
    border-left: 6px solid var(--color-warning);
    border-radius: var(--radius-box);
    background-color: var(--color-base-100);
    font-size: 0.9375rem;
  }
npm run build

The guard’s effect is in Figure 41.3, and the page in Figure 41.4.

Two groups and a card. Left, written as it was typed: =HYPERLINK, a display name a member typed; the spreadsheet runs it, a link or a call to another program; +447700900123 becomes the number 4.48E+11. Right, written by Otahque: the same formula with an apostrophe first, shown as text; every typed cell checked, names, emails, facts, answers, for = + - @, tab, CR; +44 7700 900123, spaced by Otahque, kept as text, no apostrophe. Below: CSV quotes do not help; Excel read quoted =1+1 and +447700900123 as a formula and a number.
Figure 41.3 — A cell that becomes a formula, and how the download prevents it.
Two screenshots of Attendees of Sample clinic, as Sam. Left, at 390 pixels: the places count, a Download CSV button and the text 1 row, with the columns below, then a notice with an amber edge: this list holds personal data; names, email addresses, phone numbers, and answers are for running this event only; every download is recorded; delete the file when the event is over; then the table in its card. Right, at 1280 pixels: the same, with the table showing Sai’s row.
Figure 41.4 — The attendee list with its download, at 390 and 1280 pixels.

Step 11: Records

In docs/design/registration.md, the line “- The download of the attendee table: Chapter 41.” under “Not here” becomes “- A web upload of a spreadsheet: after Chapter 44.”, and at the end:

## Download and import (Chapter 41)

- AttendeesDownloadView streams the attendee table as
  CSV, with the page's own columns (registrations/
  table.py). The same people as the page; each GET is
  an allowed download_attendees record with its row
  count. A BOM starts the file; typed text starting
  = + - @, tab, or CR gets an apostrophe; phone numbers
  are written +44 7700 900123 and not guarded.
- Registration.source: site or import. The
  import_registrations command (docs/runbooks/import.md)
  calls Event.register(..., source='import'), which
  ignores only not_open and closed.

At the end of docs/design/permissions.md:

## The attendee download (Chapter 41)

The download answers exactly as the attendee list does
(DownloadMethodTests): its organizers and the
administrator, GET and HEAD; anyone else 403, recorded,
or 404 for a hidden draft. Each GET is recorded as an
allowed download_attendees event.

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

## Update, Chapter 41

- AttendeesView and AttendeesDownloadView share
  attendees_of() for the refusal and
  registrations/table.py for the columns.
- AttendeesDownloadView is a View with get() only:
  GET, HEAD, and OPTIONS, as the list.

Three smaller edits keep earlier notes true. docs/design/erd.md gains “Chapter 41 adds, for review: - Registration.source: site or import (D41.3).” below Chapter 38’s additions. In docs/adr/ADR-004-access-rules.md, “Changing a group’s permissions needs a migration until Chapter 41 adds a command.” becomes “Changing a group’s permissions needs a migration; since Chapter 41, ensure_groups puts back the list in accounts/roles.py and reports any difference.” In docs/design/passwords-and-two-factor.md, “Exports leave the table out” becomes “Fixtures leave the table out”.

Step 12: Check and commit

uv run python check.py
== python manage.py check
System check identified no issues (0 silenced).
== python manage.py makemigrations --check --dry-run
== python manage.py test --parallel
Found 475 test(s).
System check identified no issues (0 silenced).
Ran 475 tests in ...s
OK
== all checks passed
git add .
git status --short
git commit -m "Import places and download the attendee list"
A  accounts/management/__init__.py
A  accounts/management/commands/__init__.py
A  accounts/management/commands/ensure_groups.py
A  accounts/roles.py
M  accounts/tests/test_accounts.py
A  accounts/tests/test_groups.py
A  audit/migrations/0004_download_action.py
M  audit/models.py
A  config/tests/test_fixtures.py
M  docs/adr/ADR-004-access-rules.md
M  docs/adr/ADR-006-views.md
M  docs/design/erd.md
M  docs/design/passwords-and-two-factor.md
M  docs/design/permissions.md
M  docs/design/registration.md
A  docs/runbooks/import.md
A  events/management/__init__.py
A  events/management/commands/__init__.py
A  events/management/commands/seed_demo.py
M  events/models.py
A  events/tests/test_seed.py
A  registrations/management/__init__.py
A  registrations/management/commands/__init__.py
A  registrations/management/commands/import_registrations.py
A  registrations/migrations/0006_source.py
M  registrations/models.py
A  registrations/table.py
M  registrations/templates/registrations/attendees.html
A  registrations/tests/test_download.py
A  registrations/tests/test_import.py
M  registrations/urls.py
M  registrations/views.py
M  static/otahque/site.css
M  static/otahque/source.css
[main 1a2b3c4] Import places and download the attendee list
 34 files changed, 1058 insertions(+), 54 deletions(-)
 create mode 100644 accounts/management/__init__.py
 create mode 100644 accounts/management/commands/__init__.py
 create mode 100644
    accounts/management/commands/ensure_groups.py
 create mode 100644 accounts/roles.py
 create mode 100644 accounts/tests/test_groups.py
 create mode 100644 audit/migrations/0004_download_action.py
 create mode 100644 config/tests/test_fixtures.py
 create mode 100644 docs/runbooks/import.md
 create mode 100644 events/management/__init__.py
 create mode 100644 events/management/commands/__init__.py
 create mode 100644 events/management/commands/seed_demo.py
 create mode 100644 events/tests/test_seed.py
 create mode 100644 registrations/management/__init__.py
 create mode 100644
    registrations/management/commands/__init__.py
 create mode 100644
    registrations/management/commands/import_registrations.py
 create mode 100644 registrations/migrations/0006_source.py
 create mode 100644 registrations/table.py
 create mode 100644 registrations/tests/test_download.py
 create mode 100644 registrations/tests/test_import.py

If something goes wrong

Table 41.2 — Recovery for Chapter 41
Symptom Likely cause Recovery
Unknown command: 'ensure_groups' An __init__.py missing in management/ or commands/ Add both
seed_demo: Demo data exists already It ran before Expected; the data is there
loaddata: wrong groups or permissions A fixture without natural keys Dump with --natural-foreign --natural-primary
Every import row: no email column The file starts with a BOM read as text utf-8-sig (Step 8)
Every import row: answers_needed The event asks a fact or a required question Expected; those members register on the site
The download opens with garbled names No BOM csv_lines() yields it first
A phone number shows as 4.48E+11 Written without spaces phone_cell() uses as_international
PAGE 003

Verify Your Work

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

Table 41.3 — Verification checklist for Chapter 41
Check Command or action Expected result
Starting point test --parallel Found 448 test(s); OK
Groups test accounts.tests.test_groups; ensure_groups --check Red; then 4 tests OK; Both groups match
Sample data test events.tests.test_seed; seed_demo 4 tests OK; Made 20 members, 6 events
Fixture test config.tests.test_fixtures Found 1 test(s); OK
Migrations makemigrations, then migrate registrations 0006 and audit 0004 applied
Import test registrations.tests.test_import Found 8 test(s); OK
Download test registrations.tests.test_download Red; then Found 10 test(s); OK
UI Attendee list at 390 and 1280 px; the CSV opened Download CSV and the notice; no sideways scroll; a BOM and a header
All checks uv run python check.py == all checks passed; Ran 475 tests
Commit git log --oneline -1 Import places and download the attendee list
Not verified macOS and Linux shells; browsers other than Edge; LibreOffice and Google Sheets The Excel behaviour was probed in Excel 16 only

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

PAGE 004

Checkpoint: Quiz and Challenge

Quiz

Que. 1 Why does ensure_groups read accounts/roles.py, while Chapter 30’s migration keeps its own list?

Flip to check your answerFold answer back

Answer. The command and the tests must agree on what the groups should hold today, so they share one module. A migration describes the database as it was when the migration was written; if it imported roles.py, changing the list would silently change what an old migration does on a new database.

Que. 2 What makes seed_demo produce the same data twice?

Flip to check your answerFold answer back

Answer. Fixed lists of names, topics, and places, and every random choice drawn from random.Random(seed), a generator only the command uses. The same seed gives the same sequence on every machine.

Que. 3 How does Otahque’s dry run guarantee it reports what the real import would do?

Flip to check your answerFold answer back

Answer. It is the real import: every row goes through Event.register() with its lock and rules, inside one transaction, which is then rolled back. There is no separate preview code to drift.

Que. 4 Why does the download prefix some cells with an apostrophe, but not the phone number?

Flip to check your answerFold answer back

Answer. A cell starting with =, +, -, or @ may run as a formula when the file is opened, so text a person typed gets an apostrophe. The phone number is written by Otahque from a checked number, spaced as +44 7700 900123, which spreadsheets keep as text; an apostrophe would only show up in the cell.

Que. 5 Who may download an event’s attendee list, and what does Otahque remember about it?

Flip to check your answerFold answer back

Answer. The same people who may open the list: the event’s current organizers and the administrator. Each download is an allowed download_attendees audit record, with who, which event, and how many rows.

Mini-Challenge

Write a test, in registrations/tests/test_empty.py, that the download of an event with no places holds exactly one line: the BOM and the header row. Then, as an idea only, list what a printable PDF attendee sheet would need that the CSV does not (EX-PDF-REPORT).

Hint: text_of() from test_download.py joins the streamed pieces.

Model answer:

"""An empty event's download (Chapter 41 challenge)."""
from django.test import TestCase

from config.helpers import in_group

from .test_download import text_of
from .test_registrations import soon, url


class EmptyDownloadTests(TestCase):
    """No places: a BOM and the header row, nothing else."""

    def test_only_the_header(self):
        event = soon()
        sam = in_group('sam@example.org', 'Organizers')
        event.add_organizer(sam)
        self.client.force_login(sam)
        lines = text_of(self.client.get(
            url('download', event.pk))).splitlines()
        self.assertEqual(len(lines), 1)
        self.assertTrue(lines[0].startswith('\ufeffName,'))
Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...s

OK

A PDF sheet would need a library and its fonts, a page layout that fits long names, a decision about which columns to leave out (a sheet at a front desk needs names, not answers), the same access check and download record, and a renderer that fetches no external resources. The model answer was run and then removed; the chapter’s checkpoint does not include it.

What We Learned

  • A management command is a Command class in management/commands/, with add_arguments(), handle(), self.stdout, and CommandError for exit code 1.
  • Test commands with call_command(), capturing their output.
  • Data that several parts of a project need lives in one module; migrations keep their own frozen copies.
  • Deterministic sample data comes from fixed lists and a private random.Random(seed).
  • Fixtures are for small, exact data; natural keys make them portable; they must never hold real people’s data or secrets.
  • An import runs every row through the same rules as the site; its dry run is the real run, rolled back.
  • StreamingHttpResponse sends a file as it is built; a BOM tells Excel it is UTF-8.
  • Guard every typed cell against formulas; write numbers you control in a form spreadsheets keep as text.

Key terms

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

Table 41.4 — Key terms from Chapter 41
Term Meaning
Management command Code run as manage.py name, with arguments and an exit code.
call_command() Runs a command from Python, as tests do.
Fixture A file of rows that loaddata saves exactly as written.
Natural key Values that identify a row in any database, used instead of its id.
Seed command A command that creates sample data through the models.
Dry run Doing the work, reporting it, and saving nothing.
Provenance Where a record came from: here, Registration.source.
StreamingHttpResponse A response sent piece by piece from an iterator.
CSV injection A cell that a spreadsheet runs as a formula.
Byte order mark (BOM) Bytes at the start of a file that announce its encoding.

Readiness checkpoint: you are ready for Chapter 42 when uv run python check.py ends with “all checks passed” and 475 tests, uv run python manage.py ensure_groups --check says both groups match, the demo community exists, Sam can download his attendee list and open it with names, phone numbers, and answers intact, and git log --oneline -1 shows this chapter’s commit.

Git Commit

Your Chapter 41 work was committed once, in Step 12, as “Import places and download the attendee list”: the roles module, the three commands, the source field and its migration, register()’s import rule, the download action and its migration, the table module, the views, URL, template, and styles, the tests, the runbook, and the design notes. If you kept the Mini-Challenge, commit it on its own:

git add registrations/tests/test_empty.py
git commit -m "Check an empty attendee download"
PAGE 005

Test Your Knowledge: Interview Questions

These five questions rehearse the chapter at interview level, from junior to lead. L1 to L3 check what you have just done. L4 and L5 look ahead, to a support report about a spreadsheet and to choosing how data reaches a database. They are extension questions, not a gate to the next chapter. Proof files are run with uv run python manage.py shell -v 0 -c "exec(open('NAME').read())" and deleted afterwards.

L1 (Junior): Why is the import a command, not a page?

What the interviewer is testing: Do you know when a job belongs in a command?

Flip to check your answerFold answer back

Perfect answer: The import is run by an operator, rarely, from a file on their own machine, and its output is a report to read, not a page to use. A command runs with the project’s settings and models, takes the event and the file as checked arguments, prints a line per row, and ends with an exit code that a script can act on. A page would need an upload form, the file rules of Chapter 42, a preview screen, and, for a big file, a background task (Chapter 44), all for a job a few people do a few times. The page may come later, built on the same code.

Table 41.5 — A command and a page
Question Command Page
Who runs it An operator, in a terminal A member, in a browser
Input Arguments and files on disk A form and an upload
Output Lines and an exit code HTML
Long work Runs until it finishes Needs a background task

Behind the scenes:

INSTALLED_APPS, last to first ->
  <app>/management/commands/<name>.py
  -> Command().run_from_argv(argv)

Code proof: a command called from Python, as the tests do:

Both groups match roles.py.

Common mistakes:

  • Printing with print(), which tests cannot capture; use self.stdout.write().
  • Ending with exit code 0 when rows were refused.

Follow-up the interviewer might ask:

  • How would you run it every night? (A scheduler, such as cron or a systemd timer, calling the command.)
  • Where do two apps’ commands with the same name go? (The first app in INSTALLED_APPS wins.)

L2 (Mid-Level): Predict what running the same import file twice does

What the interviewer is testing: Can you reason about an operation that may be repeated?

Flip to check your answerFold answer back

Perfect answer: The first run imports each eligible member and marks the places source='import'. The second run sends every row through register() again; members who now hold a place are refused with already_registered, which the command reports as “skipped”, not refused. So the second run imports nothing, changes nothing, and exits with 0. An operator who is not sure whether a run finished can safely run it again; that property is called idempotence.

A numbered flow of five cards. 1, run the same import file again. 2, each row calls register() again. 3, members with a place: already_registered. 4, reported as skipped, not refused. 5, imported 0: the rerun changes nothing.
Figure 41.5 — Running the same import twice.

Behind the scenes:

first: imported 2, skipped 0, refused 0
again: imported 0, skipped 2, refused 0

Code proof: two runs on a demo event, rolled back:

first: Imported 2, skipped 0, refused 0.
again: Imported 0, skipped 2, refused 0.

Common mistakes:

  • Counting repeats as errors, so a safe rerun looks like a failure.
  • Reactivating a cancelled place, which would undo a member’s own decision.

Follow-up the interviewer might ask:

  • What if a member cancelled between the runs? (They are eligible again, so the second run gives them a new place, which the operator should check.)
  • How would you make the report a file? (Write the same lines to a path given by an option.)

L3 (Senior): Defend refusing unknown emails instead of creating accounts

What the interviewer is testing: Can you defend a data boundary against a convenient shortcut?

Flip to check your answerFold answer back

Perfect answer: Sam’s spreadsheet is not consent. An account made from it would give someone a login they never asked for, a record of personal data they never agreed to, and emails they never wanted, and it would be made without a confirmed address, which every rule in Otahque relies on. Refusing the row with its reason costs Sam one message: “please sign up, then I will give you a place”. It keeps every account one that a person created. I would revisit with invitations, where Otahque sends a link and the person decides (Chapters 67 and 68).

A numbered flow of five cards. 1, goal: places for people already in Otahque. 2, an unknown email: no account to give a place to. 3, creating one would invent consent and a login. 4, refused with its reason; they sign up first. 5, revisit with invitations, Chapters 67 and 68.
Figure 41.6 — Why unknown emails are refused.

Behind the scenes:

no member            refused, no account
member, unconfirmed  refused: unverified
member, confirmed    register(..., source='import')

Code proof: the import tests:

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

OK

Common mistakes:

  • Matching addresses case-sensitively, so RAJ@example.org is “unknown”.
  • Treating an import as proof that someone attended or agreed.

Follow-up the interviewer might ask:

  • How would invitations work? (A token emailed to the address; the place is made when the person accepts.)
  • Who should see that a place was imported? (Organizers, on the list; Chapter 46 could show it.)

L4 (Staff): The venue says the file “opens with a security warning”. Diagnose it

What the interviewer is testing: Can you trace a spreadsheet warning back to the data?

Flip to check your answerFold answer back

Perfect answer: Spreadsheets warn when a file contains formulas or links that would run. In a download made from people’s input, that means a cell starts with =, +, -, or @: a display name, a company, or an answer that a member typed. I would open the file as text, find the cell, and check how it was written. In Otahque every typed cell goes through guarded(), which adds an apostrophe; a warning means a new column skipped it. The fix is to route that column through guarded() and add a hostile value to the download test, as DownloadTests does with a =HYPERLINK name.

A numbered flow of five cards. 1, the file opens with a security warning. 2, a cell starts with = or +. 3, a typed name or answer was written as it was. 4, guarded() adds an apostrophe; phones spaced. 5, a test downloads a hostile name.
Figure 41.7 — Diagnosing a formula in a download.

Behind the scenes:

Sai                 -> Sai
=HYPERLINK("...")   -> '=HYPERLINK("...")
+44 7700 900123     -> +44 7700 900123 (by Otahque)

Code proof: guarded() on four values:

'Sai' -> 'Sai'
'=1+1' -> "'=1+1"
'-1 beginner' -> "'-1 beginner"
'@SUM(A1)' -> "'@SUM(A1)"

Common mistakes:

  • Relying on CSV quotes, which spreadsheets ignore when deciding what is a formula.
  • Guarding numbers Otahque wrote itself, so an apostrophe appears in every phone cell.

Follow-up the interviewer might ask:

  • Is the apostrophe always hidden? (Not in every program, and not always after saving and reopening; OWASP’s testing guide warns of both.)
  • Would an .xlsx file avoid this? (Cells could be typed as text, at the cost of a library: D41.4 B, not chosen.)

L5 (Lead): Defend fixtures for tests and a seed command for readers

What the interviewer is testing: Can you match a data-setup tool to its job?

Flip to check your answerFold answer back

Perfect answer: Three needs, three tools. Tests need small, exact data that each test controls, written in the test as code, with a fixture only for a round trip like Step 5’s. Readers need the same realistic community on every machine, which a seed command gives: it creates rows through the models, so they obey today’s rules, and it changes with the models instead of breaking. The application needs some rows to run at all, such as the groups, which belong in a data migration, repaired by ensure_groups. A committed fixture would serve none of these well: it goes stale when models change, bypasses validation on load, and invites someone to commit real people’s data. I would revisit if loading the large seed became too slow for the load-testing chapters.

A numbered flow of five cards. 1, three needs: tests, readers, the database. 2, tests: fixtures or code, small and exact. 3, readers: seed_demo, the same every time. 4, required rows: a data migration. 5, never real people’s data in the repository.
Figure 41.8 — A tool for each kind of data.

Behind the scenes:

groups        migration, then ensure_groups
demo people   seed_demo --seed 41
test rows     the test's own code

Code proof: the fixture round trip:

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

OK

Common mistakes:

  • Loading a big fixture in every test, which makes the suite slow and hides what each test needs.
  • Seeding sample data in a migration, so every production database gets it.

Follow-up the interviewer might ask:

  • What about factories such as factory_boy? (A good tool for test data; Otahque’s helpers play that role without a dependency.)
  • How would you make the large seed faster? (Larger bulk_create() batches; measure first, in Chapter 55.)
PAGE 006