ContentsClose contents
Pre-release
Chapter 42 · File uploads and storageCHAPTER 42

Complete six-part pre-release for review. Two migrations (cover and gallery; member photo). Chapter 39's public-pages test covers the media view, and two earlier event-page tests change (declared).

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

File uploads and storage

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

Prerequisites: Chapters 9 to 41, including the Chapter 41 project with its 475 passing tests, login by default with its list of public pages (Chapter 39), an event’s visibility rule and its lock (Chapters 30 and 33), copying an event (Chapter 26), the member’s Profile (Chapters 27 and 31), and transaction.on_commit()’s idea of “after the save” (Chapter 33)

What you’ll build: Pillow, pinned, and the checks every uploaded picture passes before Otahque keeps its own copy; a cover for each event, a gallery of up to twelve described photos, and a photo for each member; one view that serves every stored file to exactly the people who may see it; old files deleted only after the change commits, and a cleanup_media command for strays; covers on event cards and pages, organizers shown with a round photo or their initials, and a gallery that opens larger without JavaScript

Why This Matters

Sam wants a picture at the top of the Python clinic’s page, and a few photos from the last clinic below it. Sai would like a face next to her name on the events she organizes. Each of those is a file from someone’s computer, and a file is the most dangerous kind of input a web application accepts.

A file named photo.jpg may not be a picture at all. A real picture may be 17 KB on disk and still claim to be 12,000 pixels square, so that opening it uses hundreds of megabytes of memory. A phone photo usually carries the GPS position where it was taken, perhaps Sai’s home. And a draft event’s cover must not be reachable by anyone who guesses its address before Sam publishes.

So this chapter does more than add a field. Every picture passes Otahque’s checks and is replaced by a copy Otahque made itself; every file is served by one view that asks the owning row who may see it; and no file is deleted until the change that replaced it has really happened.

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

  • explain how a file travels from a form to request.FILES to storage, and why enctype matters;
  • validate an uploaded picture by its content, with size and pixel limits checked before decoding;
  • re-encode a picture so that no metadata, such as a GPS position, survives;
  • store files through STORAGES with random names, and serve them through a view that authorizes each one;
  • delete replaced files only after commit, and clean up files no row names;
  • test uploads without leaving files behind.

Out of scope: object storage and a CDN (Chapter 63), a web server limit on request size (Chapter 63), the full threat model for uploads (Chapter 59), attendee photos after an event, which need moderation (Chapter 72), and the profile photo’s retention when an account is deleted (Chapter 65).

PAGE 001

What You Need to Know

From a form to storage

New Concept: file uploads

What problem exists? A form’s text fields arrive as short strings, but a picture is megabytes of bytes that must arrive whole, with its name, and be kept somewhere other than the database.

What did people do before? Stored the bytes in a database column, which made the database huge and slow to back up, or wrote them into the web server’s folder, where anyone could fetch them by name.

What is it? A form with enctype="multipart/form-data" sends each file as its own part of the request body. Django puts the text fields in request.POST and the files in request.FILES, each an UploadedFile with a name, a size, and the bytes, kept in memory up to 2.5 MB and in a temporary file above that. A model’s FileField or ImageField stores only a name, such as covers/3f9c...e1.jpg; the bytes go to a storage, configured in STORAGES, which is a folder on disk for now.

Why use it? The database keeps a short name; the storage can change, from a folder to object storage, without touching the models.

Now let’s use it. Step 2 configures the storage; Step 8 builds the form.

Follow one upload in Figure 42.1, and notice where Otahque steps in: between the bytes arriving and anything being stored.

Five numbered cards joined by arrows. 1, a form with method post and enctype multipart/form-data; without enctype the browser sends only the file name. 2, request.FILES: an UploadedFile, in memory up to 2.5 MB, else a temporary file; not a size limit. 3, cleaned_image(): Otahque’s checks, then a new copy it made itself. 4, storage, STORAGES default: FileSystemStorage under MEDIA_ROOT now; a random name such as covers/3f9c...e1.jpg. 5, the row keeps the name: Event.cover, Profile.photo, or EventPhoto.image; config.views.media serves it.
Figure 42.1 — An upload, from the form to storage.

Under the Hood: FILE_UPLOAD_MAX_MEMORY_SIZE is not a limit

The setting’s name suggests a maximum upload size, and many tutorials use it that way. It only decides where Django keeps an upload while the request is handled: in memory below 2.5 MB, in a temporary file above. A 2 GB file is accepted either way. Otahque checks each picture’s size itself, and Chapter 63 sets a limit in the web server, which can refuse a request before Django reads it.

The checks a picture passes

New Concept: Pillow and re-encoding

What problem exists? A file’s name and the type the browser claims are both chosen by the person uploading. Only the bytes say what the file is.

What did people do before? Checked the extension, which anyone can rename, or trusted content_type, which the browser reports and an attacker writes.

What is it? Pillow is the Python imaging library Django’s ImageField relies on. Image.open() reads only a picture’s header: its format and its size in pixels. Decoding the pixels happens later, and is the expensive and risky step. Otahque’s cleaned_image() checks the header, decodes the picture, and then re-encodes it: saves a brand-new file from the pixels alone. Nothing else in the original, such as its metadata, survives.

Why use it? The stored file is one Otahque wrote, in a format it chose, at a size it chose.

Now let’s use it. Step 3 writes cleaned_image(), tests first.

The checks run in the order of Figure 42.2, cheapest and safest first. The second check needs a word. A decompression bomb is a small file that declares an enormous picture: a 17 KB PNG can claim 12,000 by 12,000 pixels, 144 million, which needs hundreds of megabytes of memory to decode. Pillow has a limit, Image.MAX_IMAGE_PIXELS, about 89 million pixels, but above it Pillow only warns; it refuses only above twice the limit. The plan review tried it: Django’s own ImageField accepted that 17 KB file with a warning. Otahque turns the warning into a refusal, before a single pixel is decoded (decision N42.8).

Five numbered cards joined by arrows. 1, at most 5 MB, checked before the file is opened. 2, in red, header only, at most 89 megapixels: Pillow’s limit, refused before any pixel is decoded; a 17 KB file can declare 144. 3, in red, JPEG, PNG, or WebP: SVG, GIF, and text named photo.jpg are refused. 4, verify, decode, turn, shrink: EXIF orientation applied; at most 1600 pixels. 5, a new copy, then a random name: PNG if see-through, else JPEG; no metadata, so no GPS position.
Figure 42.2 — The checks every picture passes, in order.

In practice: EXIF, the data inside a photo

Situation. Sai uploads a photo from her phone for her profile.

Application. Phones write EXIF metadata into every photo: the camera model, the time, often the GPS position, and an orientation tag that says which way is up. Otahque applies the orientation first, so the photo is not stored sideways, then writes a new file from the pixels, which carries none of it.

Consideration. A package that resizes images may keep the metadata unless told not to; check what yours does, as Chapter 42’s test does with a GPS tag.

Serving: one view decides

Django can serve MEDIA_ROOT directly in development, and most tutorials do. But then every file is public to anyone who knows its name, and a draft event’s cover is public before Sam publishes. Otahque serves every stored file through one view, config.views.media, which finds the row that names the file and asks that row’s own rule, as Figure 42.3 shows. Because login is required by default (Chapter 39), the view is marked login_not_required: a published event’s cover must load for visitors, and the view decides each file itself.

At the top, GET /media/folder/name, config.views.media: login_not_required; finds the row that names the file, then asks that row’s rule. Three columns below. covers and gallery: published or cancelled, everyone, cached for an hour; draft, its organizers and the administrator, others 404. photos: its owner, always; anyone else, only if they may see an event the owner organizes. In red, no row names it: any viewer, 404, as for a hidden event; cleanup_media deletes it after an hour.
Figure 42.3 — Who may fetch which file.
Table 42.1 — Three pictures, one set of rules
Picture Who uploads Who sees it
Event cover The event's organizers Whoever may see the event
Gallery photo, at most 12 The event's organizers Whoever may see the event
Member photo The member The member; anyone who may see an event they organize

Files outlive transactions

A database change can be rolled back; a file deleted from disk cannot. If Otahque deleted the old cover and then the save failed, the row would still name the old file, which would be gone. So the old file is deleted with transaction.on_commit(), only once the new name is safely saved. The opposite can happen too: a file is written, then the save fails, and nothing names the file. That stray costs only disk space, and cleanup_media finds it.

Common Error: deleting a row does not delete its file

Django never deletes a stored file when its row is deleted, or when a field is given a new file; this is deliberate, because Django cannot know whether another row shares the file. Code that replaces or removes a picture must delete the old file itself, after commit, as Otahque’s replace() and EventPhoto.remove() do.

PAGE 002

How We Build It

Start from Chapter 41, in the folder containing manage.py, with Otahque on PostgreSQL 18, 475 passing tests, and the work committed (the last commit is “Import places and download the attendee list”). One package is new, Pillow 13.0.0, so Step 2 needs an internet connection once. Two migrations are new, one in events and one in accounts. The new files are events/images.py, a cleanup_media command, four templates, a widget template, six test modules, and a design note. The models, views, URLs, and forms of events and accounts, the project’s views and URLs, the settings, the test helpers, the event page and list, the profile page, the stylesheet, .gitignore, two earlier test modules, and two design notes change. The visible result: events have covers and galleries, members have photos, and organizers appear with a round photo or their initials. The chapter’s commands were checked in Windows PowerShell 5.1 and Git Bash against PostgreSQL 18.

The Custom Way

The quickest upload you will find in a tutorial is a model field, cover = models.ImageField(upload_to='covers/'), a form, and one line in the URLs that serves MEDIA_ROOT in development. It works in minutes, and it has every problem from Why This Matters: Django’s ImageField accepts the 17 KB decompression bomb with only a warning, the stored file keeps its GPS position and its uploader’s file name, a draft’s cover is public at a guessable address, and the old file stays on disk forever when the cover is replaced. Steps 3 to 10 deal with each of these in turn.

The Django Way

Step 1: Check the starting point

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

OK
git status --short
git log --oneline -1
... Import places and download the attendee list

Step 2: Pillow, and where files go

Django needs Pillow for ImageField, and Otahque’s checks use it directly. Add it, pinned to an exact version like every package; this is the one command in the chapter that needs the internet:

uv add pillow==13.0.0
Resolved 28 packages in ...
Installed 1 package in ...
 + pillow==13.0.0

Pillow is a native library, written largely in C, so it has security releases more often than most packages; Chapter 59 makes keeping it current part of the routine. Next, tell Django where uploaded files live. In config/settings.py, below STATICFILES_DIRS:

# Uploaded pictures (Chapter 42). Files are kept under
# MEDIA_ROOT and served only by config.views.media, which
# decides for each file who may see it; object storage
# replaces the default storage in Chapter 63.
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
STORAGES = {
    'default': {
        'BACKEND': 'django.core.files.storage.FileSystemStorage',
    },
    'staticfiles': {
        'BACKEND': 'django.contrib.staticfiles.storage.'
                   'StaticFilesStorage',
    },
}

STORAGES has two entries. default is where FileField and ImageField keep files; staticfiles is Django’s own setting for the CSS and JavaScript of Chapter 22, written out here only because defining STORAGES replaces both. Chapter 63 changes default to object storage, and no other line in Otahque will notice. Members’ files never go into Git, so add to .gitignore:

# Uploaded pictures (Chapter 42): members' files, never
# committed
media/

Step 3: The checks a picture passes

Tests need pictures, and they must not leave files in media/. Three helpers do both, and two apps’ tests will use them, so they go in config/helpers.py. Its imports become:

import io
import struct
import tempfile
import zlib
from datetime import UTC, datetime, timedelta

from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import Client, override_settings
from django.urls import reverse
from PIL import Image

from audit.models import AuditEvent
from events.forms import EventForm
from events.models import Event, OrganizerAssignment

and at the end of the file:

class TemporaryMedia:
    """Put each test's uploads in a folder of their own.

    Write it before TestCase. A setUp() of the test class's
    own must call super().setUp() first. The folder is
    deleted after each test, so no test sees another's
    files, and none are left in media/.
    """

    def setUp(self):
        """Point MEDIA_ROOT at a new temporary folder."""
        folder = tempfile.TemporaryDirectory()
        self.addCleanup(folder.cleanup)
        self.enterContext(
            override_settings(MEDIA_ROOT=folder.name)
        )
        super().setUp()


def picture(name='photo.jpg', size=(800, 600), kind='JPEG',
            mode='RGB', exif=None):
    """Return an uploaded picture made in memory."""
    buffer = io.BytesIO()
    extra = {'exif': exif} if exif is not None else {}
    Image.new(mode, size, 'teal').save(buffer, kind, **extra)
    return SimpleUploadedFile(name, buffer.getvalue())


def bomb():
    """Return a 1-pixel PNG whose header says 12000 x 12000.

    Decoding it would need 144 million pixels; Django's
    ImageField accepts it with only a warning (Chapter 42).
    """
    buffer = io.BytesIO()
    Image.new('L', (1, 1)).save(buffer, 'PNG')
    data = bytearray(buffer.getvalue())
    # The IHDR chunk: its type at bytes 12-15, its width and
    # height at 16-23, and its checksum at 29-32.
    data[16:24] = struct.pack('>II', 12000, 12000)
    data[29:33] = struct.pack(
        '>I', zlib.crc32(bytes(data[12:29]))
    )
    return SimpleUploadedFile('huge.png', bytes(data))

picture() draws a picture in memory, in any size, format, and mode, with any EXIF data. bomb() is the decompression bomb from the plan review: a one-pixel PNG whose header is rewritten to claim 12,000 by 12,000 pixels, with its checksum fixed so Pillow believes it. TemporaryMedia gives each test a new, empty MEDIA_ROOT, deleted afterwards.

The tests, in events/tests/test_images.py, describe every rule of Figure 42.2:

"""The checks every uploaded picture passes (Chapter 42)."""
import io

from django.core.exceptions import ValidationError
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import SimpleTestCase
from PIL import Image

from config.helpers import bomb, picture
from events.images import (
    NOT_A_PICTURE, TOO_LARGE, TOO_MANY_PIXELS, cleaned_image,
)

SVG = b'<svg xmlns="http://www.w3.org/2000/svg"></svg>'


def refusal(upload):
    """Return the message cleaned_image() refuses with."""
    try:
        cleaned_image(upload)
    except ValidationError as error:
        return error.messages[0]
    return None


def reopened(content):
    """Open Otahque's copy as a picture again."""
    return Image.open(io.BytesIO(content.read()))


class RefusedTests(SimpleTestCase):
    """Files that are not safe pictures are refused."""

    def test_text_named_like_a_picture(self):
        upload = SimpleUploadedFile('photo.jpg', b'not one')
        self.assertEqual(refusal(upload), NOT_A_PICTURE)

    def test_an_svg_drawing(self):
        upload = SimpleUploadedFile('logo.svg', SVG)
        self.assertEqual(refusal(upload), NOT_A_PICTURE)

    def test_a_format_not_allowed(self):
        upload = picture('photo.gif', kind='GIF', mode='P')
        self.assertEqual(refusal(upload), NOT_A_PICTURE)

    def test_more_than_5_mb(self):
        upload = SimpleUploadedFile(
            'photo.jpg', b'0' * (5 * 1024 * 1024 + 1)
        )
        self.assertEqual(refusal(upload), TOO_LARGE)

    def test_a_decompression_bomb(self):
        self.assertEqual(refusal(bomb()), TOO_MANY_PIXELS)


class CopyTests(SimpleTestCase):
    """What Otahque keeps is a new copy it made."""

    def test_location_data_is_removed(self):
        exif = Image.Exif()
        exif[0x010F] = 'Phone maker'
        exif[0x8825] = {1: 'N', 2: (53.0, 48.0, 1.0)}
        upload = picture(exif=exif)
        self.assertIn(0x8825, Image.open(upload).getexif())
        upload.seek(0)
        copy = reopened(cleaned_image(upload))
        self.assertEqual(len(copy.getexif()), 0)

    def test_a_large_picture_is_made_smaller(self):
        upload = picture(size=(4000, 3000))
        copy = reopened(cleaned_image(upload))
        self.assertEqual(copy.size, (1600, 1200))

    def test_a_sideways_phone_photo_is_turned(self):
        exif = Image.Exif()
        exif[0x0112] = 6
        copy = reopened(cleaned_image(picture(exif=exif)))
        self.assertEqual(copy.size, (600, 800))

    def test_a_see_through_png_stays_png(self):
        upload = picture('logo.png', kind='PNG', mode='RGBA')
        content = cleaned_image(upload)
        self.assertEqual(content.name, 'picture.png')
        self.assertEqual(reopened(content).format, 'PNG')
uv run python manage.py test events.tests.test_images
Found 1 test(s).
Creating test database for alias 'default'...
ERROR: test_images
ModuleNotFoundError: No module named 'events.images'
Ran 1 test in ...s

FAILED (errors=1)

Now the checks, in a new file events/images.py:

"""The checks every uploaded picture passes (Chapter 42).

Covers, members' photos, and gallery photos all come here.
A picture is a file from a stranger's computer, so Otahque
keeps only a new copy that it made itself.
"""
import io
import uuid
import warnings

from django.core.exceptions import ValidationError
from django.core.files.base import ContentFile
from PIL import Image, ImageOps, UnidentifiedImageError

MAX_BYTES = 5 * 1024 * 1024
LONGEST_SIDE = 1600
FORMATS = {'JPEG', 'PNG', 'WEBP'}
NOT_A_PICTURE = 'Choose a JPEG, PNG, or WebP picture.'
TOO_LARGE = 'Choose a picture of 5 MB or less.'
TOO_MANY_PIXELS = ('This picture has too many pixels. Choose '
                   'one of at most 89 megapixels.')


def opened(upload):
    """Open the picture, reading only its header.

    Pillow warns, but does not refuse, between its pixel
    limit (Image.MAX_IMAGE_PIXELS) and twice that limit;
    Otahque refuses both, before any pixel is decoded.
    """
    with warnings.catch_warnings():
        warnings.simplefilter(
            'error', Image.DecompressionBombWarning
        )
        try:
            return Image.open(upload)
        except (Image.DecompressionBombWarning,
                Image.DecompressionBombError):
            raise ValidationError(TOO_MANY_PIXELS) from None
        except (UnidentifiedImageError, OSError):
            raise ValidationError(NOT_A_PICTURE) from None


def cleaned_image(upload):
    """Return a safe copy of an uploaded picture.

    Raise ValidationError if it is too large, has too many
    pixels, or is not a JPEG, PNG, or WebP picture. The copy
    is turned the right way up, at most LONGEST_SIDE pixels
    wide and high, and has no metadata (no GPS position).
    """
    if upload.size > MAX_BYTES:
        raise ValidationError(TOO_LARGE)
    image = opened(upload)
    if image.format not in FORMATS:
        raise ValidationError(NOT_A_PICTURE)
    try:
        image.verify()
        upload.seek(0)
        image = Image.open(upload)
        image = ImageOps.exif_transpose(image)
        image.thumbnail((LONGEST_SIDE, LONGEST_SIDE))
    except (OSError, SyntaxError, ValueError):
        raise ValidationError(NOT_A_PICTURE) from None
    return encoded(image)


def encoded(image):
    """Save image again: PNG if it is see-through, else JPEG.

    Only the pixels are written, so no metadata survives.
    """
    buffer = io.BytesIO()
    if image.mode in ('RGBA', 'LA', 'P'):
        image.convert('RGBA').save(buffer, 'PNG')
        extension = 'png'
    else:
        image.convert('RGB').save(buffer, 'JPEG', quality=85)
        extension = 'jpg'
    return ContentFile(buffer.getvalue(),
                       name=f'picture.{extension}')


def stored_name(folder, filename):
    """Return a random name in folder, keeping the extension.

    The member's own file name is never used: it may hold
    their name, or characters a file system dislikes.
    """
    extension = filename.rsplit('.', 1)[-1].lower()
    return f'{folder}/{uuid.uuid4().hex}.{extension}'


def cover_name(instance, filename):
    """Name an event's cover file."""
    return stored_name('covers', filename)


def photo_name(instance, filename):
    """Name a member's photo file."""
    return stored_name('photos', filename)


def gallery_name(instance, filename):
    """Name a gallery photo file."""
    return stored_name('gallery', filename)

Read opened() first. Inside warnings.catch_warnings(), Pillow’s DecompressionBombWarning is raised as an error, so a picture over the limit is refused as it is opened; above twice the limit Pillow raises DecompressionBombError itself. verify() checks the file’s structure but leaves the image unusable, so the file is opened a second time to decode it. exif_transpose() turns the picture the right way up from its orientation tag, and thumbnail() shrinks it in place, never enlarging. encoded() writes a new file from the pixels alone. The three name functions give every stored file a random name in its folder: a member’s own file name might hold their name, or characters a file system dislikes, and a random name cannot be guessed.

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

OK

Common Error: catching only DecompressionBombError

Many examples catch Image.DecompressionBombError and stop there. Pillow raises it only above twice MAX_IMAGE_PIXELS; between the limit and twice the limit it issues a warning, prints a line, and decodes anyway. test_a_decompression_bomb uses a picture in exactly that range.

Step 4: Fields, names, and the gallery

In events/models.py, below the import of audit.models:

from .images import cover_name, gallery_name

below CAPACITY_MESSAGE:

GALLERY_LIMIT = 12
GALLERY_FULL = ('This gallery has 12 photos, the most it can '
                'hold. Remove one first.')

and in Event, below asks_website:

    # Chapter 42: the picture at the top of the event page,
    # always a copy Otahque made (events/images.py).
    cover = models.ImageField(upload_to=cover_name, blank=True)

An ImageField stores a name, at most 100 characters; upload_to is the function from Step 3 that chooses it. blank=True makes the cover optional. In Event, above places_taken(), the gallery’s one way in:

    def add_photo(self, image, alt_text):
        """Add a gallery photo, or raise ValidationError.

        The count is read under the event's lock, so two
        organizers cannot both add the thirteenth photo.
        """
        with transaction.atomic():
            event = self.locked()
            if event.photos.count() >= GALLERY_LIMIT:
                raise ValidationError(GALLERY_FULL)
            return event.photos.create(
                image=image, alt_text=alt_text,
                position=event.photos.count() + 1,
            )

The count is read on the locked row (Chapter 33), so two organizers adding photos at the same moment cannot both add the thirteenth. Then the gallery’s model, above class OrganizerAssignment:

class EventPhoto(models.Model):
    """A photo in an event's gallery, added by an organizer."""

    event = models.ForeignKey(
        Event, on_delete=models.CASCADE, related_name='photos',
    )
    image = models.ImageField(upload_to=gallery_name)
    alt_text = models.CharField(
        'description', max_length=200,
        help_text='What the photo shows, for people who '
                  'cannot see it.',
    )
    position = models.PositiveIntegerField(default=0)
    added_at = models.DateTimeField(default=timezone.now)

    class Meta:
        ordering = ['position', 'pk']

    def __str__(self):
        return self.alt_text

The description is required: it is the photo’s alt text, what a screen reader says instead of showing it. In accounts/models.py, import the name function with from events.images import photo_name, and add to Profile, below website:

    # Chapter 42: shown beside the member's name on the
    # events they organize; a copy Otahque made.
    photo = models.ImageField(upload_to=photo_name, blank=True)
uv run python manage.py makemigrations -n pictures events
uv run python manage.py makemigrations -n photo accounts
uv run python manage.py migrate
Migrations for 'events':
  events\migrations\0010_pictures.py
    + Add field cover to event
    + Create model EventPhoto
Migrations for 'accounts':
  accounts\migrations\0007_photo.py
    + Add field photo to profile
Operations to perform:
  Apply all migrations: account, accounts, admin, audit,
    auth, contenttypes, events, mfa, registrations, sessions,
    socialaccount
Running migrations:
  Applying accounts.0007_photo... OK
  Applying events.0010_pictures... OK

The columns hold names, not files: existing events and profiles get an empty name, which means “no picture”.

Step 5: One view for every file

Chapter 39’s test lists the pages anyone may open. The media view will be one of them, so the test changes first, on purpose. In config/tests/test_public.py, add URLPattern to the import from django.urls, add the line “Chapter 42 adds the media view, which decides per file.” to the docstring, and replace the list and own_pages() with:

# The pages anyone may open, signed in or not.
PUBLIC = {'events:home', 'events:list', 'events:detail',
          'media'}


def own_pages():
    """Yield each page of Otahque's apps: name, route, view."""
    for app in ('accounts', 'events', 'registrations'):
        urls = import_module(f'{app}.urls')
        for pattern in urls.urlpatterns:
            yield (f'{app}:{pattern.name}', str(pattern.pattern),
                   pattern.callback)
    # The project's own pages; include() lines are skipped.
    for pattern in import_module('config.urls').urlpatterns:
        if isinstance(pattern, URLPattern):
            yield (pattern.name, str(pattern.pattern),
                   pattern.callback)

The project’s own URLs are walked too now; lines that include() another app’s URLs are skipped, because those apps’ own lists cover them.

uv run python manage.py test config.tests.test_public
Found 3 test(s).
Creating test database for alias 'default'...
FAIL: test_exactly_these_pages_are_public
AssertionError: Items in the second set but not the first:
Ran 3 tests in ...s

FAILED (failures=1)

The view goes in config/views.py, because it serves files of every app. Change the docstring to “Views for the whole project (Chapters 39 and 42).”, replace the imports with:

from django.conf import settings
from django.contrib.auth.decorators import (
    login_not_required,
)
from django.core.files.storage import default_storage
from django.http import (
    FileResponse, Http404, HttpResponseServerError,
)
from django.shortcuts import get_object_or_404
from django.template import loader
from django.views.decorators.http import require_safe

from accounts.models import Profile
from events.models import Event, EventPhoto

and add at the end:

def may_see(path, user):
    """Return whether user may fetch the stored file at path.

    Each file belongs to one row, and the row's own rule
    decides: an event's cover and gallery follow the event
    page; a photo is seen by its owner, and by anyone who
    may see an event its owner organizes. A file no row
    names is not found.
    """
    folder = path.split('/')[0]
    if folder == 'covers':
        event = get_object_or_404(Event, cover=path)
        return event.is_visible_to(user)
    if folder == 'gallery':
        photo = get_object_or_404(EventPhoto, image=path)
        return photo.event.is_visible_to(user)
    if folder == 'photos':
        profile = get_object_or_404(Profile, photo=path)
        if profile.user == user:
            return True
        events = Event.objects.organized_by(profile.user)
        return any(e.is_visible_to(user) for e in events)
    raise Http404('No such file.')


@login_not_required
@require_safe
def media(request, folder, name):
    """Send an uploaded picture to those who may see it.

    Public even under login-by-default (Chapter 39), because
    published events' pictures are; may_see() decides each
    file. Others get 404, as for a hidden event.
    """
    path = f'{folder}/{name}'
    if not may_see(path, request.user):
        raise Http404('No such file.')
    if not default_storage.exists(path):
        raise Http404('No such file.')
    response = FileResponse(default_storage.open(path))
    return response

may_see() is the whole access rule of Figure 42.3. The folder says which kind of row owns the file; get_object_or_404() finds the row by the name it stores, so a file no row names is not found, even if it is on disk. Each kind of row then uses a rule Otahque already has: an event’s visibility for covers and gallery photos, and for photos, the owner or anyone who may see an event the owner currently organizes. require_safe allows only GET and HEAD. In config/urls.py, add from . import views below the Django imports, and below the registrations line:

    path('media/<str:folder>/<str:name>', views.media,
         name='media'),

The str converter never matches a /, so no address can reach outside the three folders, and a name such as .. finds no row.

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

OK

MEDIA_URL is /media/, so event.cover.url is exactly an address this view answers; templates use .url, and never build addresses by hand.

Step 6: Cache headers

Browsers keep pictures between pages when the response says they may. A stored name is random and never reused, so a public picture can be kept safely: a new cover gets a new name. A private one must be checked again each time, or a browser could keep showing a draft’s cover after the viewer lost access. In config/views.py, add from django.contrib.auth.models import AnonymousUser to the imports, and in media(), before return response:

    # Names are random and never reused, so a browser may
    # keep a public picture; a private one is checked again.
    if may_see(path, AnonymousUser()):
        response['Cache-Control'] = 'public, max-age=3600'
    else:
        response['Cache-Control'] = 'private, no-cache'

A picture is public when a signed-out visitor may see it. X-Content-Type-Options: nosniff is sent already, by Django’s SecurityMiddleware: it stops a browser from deciding that a file is something other than its stated type. Step 8’s tests check both headers.

Step 7: Delete after commit

In events/images.py, add from django.db import transaction to the imports, and at the end:

def delete_later(field_file):
    """Delete a stored file once the transaction commits.

    If the transaction is rolled back, the file stays, and
    the row that still names it keeps working.
    """
    name, storage = field_file.name, field_file.storage
    if name:
        transaction.on_commit(lambda: storage.delete(name))


def replace(instance, field, content):
    """Store content in field, or clear it if content is None.

    The old file is deleted after the save commits.
    """
    with transaction.atomic():
        old = getattr(instance, field)
        delete_later(old)
        setattr(instance, field, content or '')
        instance.save(update_fields=[field])

delete_later() reads the name and the storage at once, while they are still the old file’s, and deletes the file only when the transaction commits. Outside a transaction, on_commit() runs the function immediately. replace() is the only way Otahque changes a picture field: the old file is scheduled for deletion and the field saved, in one transaction. In events/models.py, the import becomes:

from .images import cover_name, delete_later, gallery_name

EventPhoto gets a method, below __str__():

    def remove(self):
        """Delete the photo; its file goes after commit."""
        with transaction.atomic():
            delete_later(self.image)
            self.delete()

and delete_draft() deletes a draft’s pictures with it:

    def delete_draft(self):
        """Delete a draft nobody registered for."""
        if self.status != self.Status.DRAFT:
            raise ValidationError(
                'Only a draft can be deleted.'
            )
        if self.registrations.exists():
            raise ValidationError(
                'This draft has registrations, so it '
                'is kept.'
            )
        with transaction.atomic():
            delete_later(self.cover)
            for photo in self.photos.all():
                delete_later(photo.image)
            self.organizer_assignments.all().delete()
            self.questions.all().delete()
            self.delete()

The rows of the gallery go with the event, through the foreign key’s CASCADE; their files are scheduled first, while the rows can still be read. Check that everything imports:

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

Step 8: The pictures page

An event’s organizers manage its cover and gallery on one page. The forms, at the end of events/forms.py, with from .images import cleaned_image added to its imports:

PICTURE_HELP = ('JPEG, PNG, or WebP, up to 5 MB. Otahque keeps '
                'a copy at most 1600 pixels wide, without '
                'location or camera details.')


class PictureForm(forms.Form):
    """One uploaded picture, checked by cleaned_image().

    A FileField, not an ImageField: Django's ImageField
    decodes the file itself, before Otahque's checks.
    """

    image = forms.FileField(
        label='Picture', help_text=PICTURE_HELP,
        widget=forms.FileInput(attrs={
            'accept': 'image/jpeg,image/png,image/webp',
        }),
    )

    def clean_image(self):
        """Return Otahque's own copy of the picture."""
        return cleaned_image(self.cleaned_data['image'])


class GalleryPhotoForm(PictureForm):
    """A gallery photo and what it shows (Chapter 42)."""

    alt_text = forms.CharField(
        label='Description', max_length=200,
        help_text='What the photo shows, for people who '
                  'cannot see it.',
    )

The field is a FileField, not Django’s forms.ImageField, because forms.ImageField opens and verifies the file itself, before clean_image() can refuse a bomb. accept asks the browser to offer only pictures; it is a convenience for the member, not a check. In events/views.py, the imports change to:

from django.views.decorators.http import (
    require_http_methods, require_POST,
)

from audit.models import AuditEvent, record
from registrations.forms import QuestionFormSet

from .forms import (
    CopyForm, EventFilterForm, EventForm, GalleryPhotoForm,
    MyEventsForm, OrganizerForm, PictureForm,
    RemoveOrganizerForm, VersionForm,
)
from .images import replace
from .models import (
    GALLERY_FULL, GALLERY_LIMIT, REASONS, Event,
    OrganizerAssignment,
)

and at the end:

@require_http_methods(['GET', 'POST'])
def event_pictures(request, event_id):
    """Show and change the cover and gallery, for organizers.

    One page, three forms; each POST names its action. Every
    change is recorded as an edit of the event.
    """
    event = event_to_manage(request, event_id,
                            Action.EDIT_EVENT)
    cover = PictureForm(prefix='cover')
    photo = GalleryPhotoForm(prefix='photo')
    action = request.POST.get('action')
    if action == 'cover':
        cover = PictureForm(request.POST, request.FILES,
                            prefix='cover')
        if cover.is_valid():
            replace(event, 'cover', cover.cleaned_data['image'])
            return saved(request, event, 'cover',
                         'Cover saved.')
    elif action == 'remove_cover' and event.cover:
        replace(event, 'cover', None)
        return saved(request, event, 'cover', 'Cover removed.')
    elif action == 'photo':
        photo = GalleryPhotoForm(request.POST, request.FILES,
                                 prefix='photo')
        if photo.is_valid():
            try:
                event.add_photo(photo.cleaned_data['image'],
                                photo.cleaned_data['alt_text'])
            except ValidationError as error:
                photo.add_error(None, error)
            else:
                return saved(request, event, 'photos',
                             'Photo added.')
    return render(request, 'events/pictures.html', {
        'event': event, 'cover': cover, 'photo': photo,
        'photos': event.photos.all(), 'limit': GALLERY_LIMIT,
        'full': GALLERY_FULL,
    })


def saved(request, event, field, message):
    """Record the change, say so, and show the page again."""
    record(request.user, Action.EDIT_EVENT, event,
           fields=[field])
    messages.success(request, message)
    return redirect('events:pictures', event.pk)


@require_POST
def remove_photo(request, event_id, photo_id):
    """Remove one gallery photo, for the event's organizers."""
    event = event_to_manage(request, event_id,
                            Action.EDIT_EVENT)
    photo = get_object_or_404(event.photos, pk=photo_id)
    photo.remove()
    return saved(request, event, 'photos', 'Photo removed.')

event_to_manage() is the edit page’s own check, so the page answers exactly as the edit page does: 404 for a hidden draft, 403 for a member who may not edit it, both recorded. Each form has a prefix, so the two image fields do not share a name, and each submit button sends an action. request.FILES is passed to the form beside request.POST; without it, the file field is always empty. Every change is recorded as an edit of the event, with the field that changed. In events/urls.py, below the copy line:

    path('events/<int:event_id>/pictures/',
         views.event_pictures, name='pictures'),
    path('events/<int:event_id>/pictures/<int:photo_id>/'
         'remove/', views.remove_photo, name='remove_photo'),

The template, events/templates/events/pictures.html:

{% extends "base.html" %}

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

{% block content %}
  <h1>Pictures of {{ event.title }}</h1>
  <p>Pictures are public once the event is published, like
     the rest of its page. Until then, only its organizers
     and the administrator can see them.</p>
  <section class="card space-y-4 border border-base-300
                  bg-base-100 p-6" aria-labelledby="cover-h">
    <h2 id="cover-h" class="text-lg font-semibold">Cover</h2>
    {% if event.cover %}
      <img class="cover-preview" src="{{ event.cover.url }}"
           alt="The current cover">
    {% else %}
      <p class="text-sm">No cover yet.</p>
    {% endif %}
    <form method="post" enctype="multipart/form-data"
          class="space-y-4">
      {% csrf_token %}
      {{ cover }}
      <div class="form-actions">
        <button type="submit" name="action" value="cover"
                class="btn btn-primary">
          {% if event.cover %}Replace cover{% else %}
          Upload cover{% endif %}</button>
      </div>
    </form>
    {% if event.cover %}
      <form method="post">
        {% csrf_token %}
        <button type="submit" name="action"
                value="remove_cover" class="btn btn-outline">
          Remove cover</button>
      </form>
    {% endif %}
  </section>
  <section class="card space-y-4 border border-base-300
                  bg-base-100 p-6" aria-labelledby="gallery-h">
    <h2 id="gallery-h" class="text-lg font-semibold">Gallery</h2>
    <p class="text-sm">{{ photos|length }} of {{ limit }}
       photos.</p>
    {% if photos %}
      <ul class="gallery-grid">
        {% for item in photos %}
          {% url 'events:remove_photo' event.pk item.pk as to %}
          <li class="gallery-item">
            <img src="{{ item.image.url }}"
                 alt="{{ item.alt_text }}" loading="lazy">
            <form method="post" action="{{ to }}">
              {% csrf_token %}
              <button type="submit" class="btn btn-sm">
                Remove</button>
            </form>
          </li>
        {% endfor %}
      </ul>
    {% endif %}
    {% if photos|length < limit %}
      <form method="post" enctype="multipart/form-data"
            class="space-y-4">
        {% csrf_token %}
        {{ photo }}
        <div class="form-actions">
          <button type="submit" name="action" value="photo"
                  class="btn btn-primary">Add photo</button>
        </div>
      </form>
    {% else %}
      <p>{{ full }}</p>
    {% endif %}
  </section>
  <p>
    <a href="{{ event.get_absolute_url }}">
      Back to the event</a>
  </p>
{% endblock %}

Both upload forms say enctype="multipart/form-data"; the remove forms send no file and do not need it. The {% url ... as to %} form keeps a long address on its own line. File inputs get daisyUI’s file-input style from a widget template of their own, templates/django/forms/widgets/file.html, beside the one that styles text inputs:

{% load otahque_widgets %}
{# Chapter 42: daisyUI's own style for choosing a file. #}
<input type="file" name="{{ widget.name }}"
       {{ widget.attrs|with_class:"file-input w-full" }}>

On the event page, organizers need a way in. In events/templates/events/detail.html, below the “Copy as a new draft” link:

          <a href="{% url 'events:pictures' event.pk %}">
            Cover and photos</a>

The tests, in events/tests/test_pictures.py:

"""Covers and the gallery: who may upload, who may see.

Chapter 42. Files go to a temporary folder (TemporaryMedia).
"""
from datetime import timedelta

from django.core.files.storage import default_storage
from django.db import transaction
from django.test import TestCase
from django.urls import reverse
from django.utils import timezone

from audit.models import AuditEvent
from accounts.models import User
from config.helpers import (
    TemporaryMedia, admin_url, in_group, picture, save_event,
)
from events.images import cleaned_image, replace
from events.models import GALLERY_FULL, GALLERY_LIMIT, Event


def pictures(event):
    """Return the address of an event's pictures page."""
    return reverse('events:pictures', args=[event.pk])


def fetch(client, address):
    """Get a stored file, reading it to the end as browsers do.

    Reading to the end closes the file: on Windows an open
    file cannot be deleted, so the test could not clean up
    its folder. Do not call page.close(): it tells Django
    the request finished, which closes the database
    connection the test is still using.
    """
    page = client.get(address)
    if page.streaming:
        b''.join(page.streaming_content)
    return page


def upload_cover(client, event):
    """Send a cover through the pictures page."""
    return client.post(pictures(event), {
        'action': 'cover', 'cover-image': picture(),
    })


def add_photo(client, event, alt='Sam at the whiteboard'):
    """Send a gallery photo through the pictures page."""
    return client.post(pictures(event), {
        'action': 'photo', 'photo-image': picture(),
        'photo-alt_text': alt,
    })


class CoverTests(TemporaryMedia, TestCase):
    """Organizers upload a cover; the event's rule shows it."""

    @classmethod
    def setUpTestData(cls):
        cls.sam = in_group('sam@example.org', 'Organizers')
        cls.raj = in_group('raj@example.org', 'Organizers')
        cls.draft = save_event(status=Event.Status.DRAFT)
        cls.draft.add_organizer(cls.sam)

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

    def test_an_organizer_uploads_a_cover(self):
        with self.captureOnCommitCallbacks(execute=True):
            page = upload_cover(self.client, self.draft)
        self.assertRedirects(page, pictures(self.draft))
        self.draft.refresh_from_db()
        self.assertTrue(self.draft.cover.name.startswith(
            'covers/'))
        self.assertTrue(default_storage.exists(
            self.draft.cover.name))
        change = AuditEvent.objects.latest('pk')
        self.assertEqual(change.detail, {'fields': ['cover']})

    def test_another_organizer_is_refused(self):
        self.client.force_login(self.raj)
        page = upload_cover(self.client, self.draft)
        self.assertEqual(page.status_code, 404)
        self.draft.refresh_from_db()
        self.assertEqual(self.draft.cover.name, '')

    def test_a_drafts_cover_is_hidden_from_others(self):
        upload_cover(self.client, self.draft)
        self.draft.refresh_from_db()
        address = self.draft.cover.url
        self.assertEqual(fetch(self.client, address).status_code,
                         200)
        self.client.logout()
        self.assertEqual(fetch(self.client, address).status_code,
                         404)
        self.client.force_login(self.raj)
        self.assertEqual(fetch(self.client, address).status_code,
                         404)

    def test_a_published_cover_is_public_and_cached(self):
        upload_cover(self.client, self.draft)
        self.draft.refresh_from_db()
        Event.objects.filter(pk=self.draft.pk).update(
            status=Event.Status.PUBLISHED)
        self.client.logout()
        page = fetch(self.client, self.draft.cover.url)
        self.assertEqual(page.status_code, 200)
        self.assertEqual(page['Content-Type'], 'image/jpeg')
        self.assertEqual(page['Cache-Control'],
                         'public, max-age=3600')
        self.assertEqual(page['X-Content-Type-Options'],
                         'nosniff')

    def test_a_private_picture_is_not_kept(self):
        upload_cover(self.client, self.draft)
        self.draft.refresh_from_db()
        page = fetch(self.client, self.draft.cover.url)
        self.assertEqual(page['Cache-Control'],
                         'private, no-cache')

    def test_a_file_no_row_names_is_not_found(self):
        default_storage.save('covers/stray.jpg',
                             cleaned_image(picture()))
        page = fetch(self.client, '/media/covers/stray.jpg')
        self.assertEqual(page.status_code, 404)

    def test_a_bad_file_is_refused_with_its_reason(self):
        page = self.client.post(pictures(self.draft), {
            'action': 'cover',
            'cover-image': picture('logo.gif', kind='GIF',
                                   mode='P'),
        })
        self.assertContains(
            page, 'Choose a JPEG, PNG, or WebP picture.')


class ReplaceTests(TemporaryMedia, TestCase):
    """The old file goes only once the new one is saved."""

    def setUp(self):
        super().setUp()
        self.event = save_event()
        replace(self.event, 'cover', cleaned_image(picture()))
        self.old = self.event.cover.name

    def test_replacing_deletes_the_old_file_after_commit(self):
        with self.captureOnCommitCallbacks(execute=True):
            replace(self.event, 'cover',
                    cleaned_image(picture()))
        self.assertFalse(default_storage.exists(self.old))
        self.assertTrue(default_storage.exists(
            self.event.cover.name))

    def test_a_rolled_back_change_keeps_the_old_file(self):
        with self.captureOnCommitCallbacks(execute=True):
            with transaction.atomic():
                replace(self.event, 'cover', None)
                transaction.set_rollback(True)
        self.event.refresh_from_db()
        self.assertEqual(self.event.cover.name, self.old)
        self.assertTrue(default_storage.exists(self.old))


class GalleryTests(TemporaryMedia, TestCase):
    """Organizers add up to twelve photos, each described."""

    @classmethod
    def setUpTestData(cls):
        cls.sam = in_group('sam@example.org', 'Organizers')
        cls.event = save_event(
            starts_at=timezone.now() + timedelta(days=7))
        cls.event.add_organizer(cls.sam)

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

    def test_a_photo_needs_a_description(self):
        page = add_photo(self.client, self.event, alt='')
        self.assertContains(page, 'This field is required.')
        self.assertEqual(self.event.photos.count(), 0)

    def test_the_thirteenth_photo_is_refused(self):
        for _ in range(GALLERY_LIMIT):
            self.event.add_photo(cleaned_image(picture()), 'A')
        page = add_photo(self.client, self.event)
        self.assertContains(page, GALLERY_FULL)
        self.assertEqual(self.event.photos.count(),
                         GALLERY_LIMIT)

    def test_removing_a_photo_removes_its_file(self):
        add_photo(self.client, self.event)
        photo = self.event.photos.get()
        address = reverse('events:remove_photo',
                          args=[self.event.pk, photo.pk])
        with self.captureOnCommitCallbacks(execute=True):
            self.client.post(address)
        self.assertEqual(self.event.photos.count(), 0)
        self.assertFalse(default_storage.exists(
            photo.image.name))


class DeleteTests(TemporaryMedia, TestCase):
    """A deleted draft leaves no file behind."""

    def test_deleting_a_draft_deletes_its_files(self):
        draft = save_event(status=Event.Status.DRAFT)
        replace(draft, 'cover', cleaned_image(picture()))
        photo = draft.add_photo(cleaned_image(picture()), 'A')
        names = [draft.cover.name, photo.image.name]
        with self.captureOnCommitCallbacks(execute=True):
            draft.delete_draft()
        for name in names:
            self.assertFalse(default_storage.exists(name))


class AdminTests(TestCase):
    """The admin cannot upload a cover past the checks."""

    def test_the_event_page_has_no_file_field(self):
        soni = User.objects.create_superuser(
            'soni@example.org', display_name='Soni')
        self.client.force_login(soni)
        page = self.client.get(
            admin_url(Event, 'change', save_event().pk))
        self.assertEqual(page.status_code, 200)
        self.assertNotContains(page, 'type="file"')
uv run python manage.py test events.tests.test_pictures
Found 14 test(s).
Creating test database for alias 'default'...
...
Ran 14 tests in ...s

OK

Three details in the tests matter beyond this chapter. fetch() reads each file response to the end, which closes its file: Windows will not delete an open file, so TemporaryMedia could not clean up. Calling response.close() instead would also close the file, but it tells Django the request has finished, and Django then closes the database connection the test is still using; on PostgreSQL every later query in the test fails with “the connection is closed”. captureOnCommitCallbacks(execute=True) runs the on-commit functions that a TestCase, which never commits, would otherwise drop. And AdminTests checks that the admin’s event page has no file field: EventAdmin lists its fields one by one, so the cover is not among them, and no picture can reach storage without passing cleaned_image().

Common Error: a form without enctype

Without enctype="multipart/form-data", the browser sends the form as plain text: request.POST holds the file’s name and request.FILES is empty, so the form says the picture is required although one was chosen. Interview question L1 shows both requests.

Step 9: A copy gets its own cover

Chapter 26 promised that a copied event carries its cover (decision 26-P13). The test, in events/tests/test_copies.py:

"""A copied event's cover is its own file (Chapter 42)."""
from datetime import timedelta

from django.core.files.storage import default_storage
from django.test import TestCase

from config.helpers import (
    TemporaryMedia, in_group, picture, save_event,
)
from events.images import cleaned_image, replace


class CopyTests(TemporaryMedia, TestCase):
    """A copy owns its cover; the gallery stays behind."""

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

    def test_a_copy_has_its_own_cover_and_no_gallery(self):
        event = save_event()
        replace(event, 'cover', cleaned_image(picture()))
        event.add_photo(cleaned_image(picture()), 'The room')
        copy = event.copy_as_draft(
            self.sam, event.starts_at + timedelta(days=28))
        self.assertTrue(copy.cover)
        self.assertNotEqual(copy.cover.name, event.cover.name)
        self.assertEqual(copy.photos.count(), 0)
        with self.captureOnCommitCallbacks(execute=True):
            replace(copy, 'cover', None)
        self.assertTrue(default_storage.exists(
            event.cover.name))
uv run python manage.py test events.tests.test_copies
Found 1 test(s).
Creating test database for alias 'default'...
FAIL: test_a_copy_has_its_own_cover_and_no_gallery
AssertionError: <ImageFieldFile: None> is not true
Ran 1 test in ...s

FAILED (failures=1)

The copy must not share the file: if it did, replacing either event’s cover would delete the other’s. In events/models.py, add from django.core.files.base import ContentFile to the imports, and in copy_as_draft(), below copy.add_organizer(member):

            if self.cover:
                # Its own file, so either may change later.
                with self.cover.open('rb') as old:
                    copy.cover.save(self.cover.name,
                                    ContentFile(old.read()))

FieldFile.save() stores the bytes under a new random name, through upload_to, and saves the row. The gallery stays with the old event: its photos show that event, not the next one (D42.6).

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

OK

Step 10: cleanup_media

A file with no row can still appear: a save that fails after its file was written, or a row deleted in the admin or the shell. The command, in events/management/commands/cleanup_media.py:

"""Delete stored pictures that no row names (Chapter 42).

A file can be left behind when a save fails after the file
was written, or when a row is deleted outside Otahque's own
code, such as in the admin. Files newer than an hour are
kept, because their row may not be saved yet.
"""
from datetime import timedelta

from django.core.files.storage import default_storage
from django.core.management.base import BaseCommand
from django.utils import timezone

from accounts.models import Profile
from events.models import Event, EventPhoto

FOLDERS = ['covers', 'gallery', 'photos']


def named_files():
    """Return the names of every file a row points to."""
    names = set(Event.objects.values_list('cover', flat=True))
    names |= set(EventPhoto.objects.values_list('image',
                                                flat=True))
    names |= set(Profile.objects.values_list('photo',
                                             flat=True))
    return names


def strays(older_than):
    """Yield stored files no row names, older than the time."""
    named = named_files()
    for folder in FOLDERS:
        if not default_storage.exists(folder):
            continue
        for file in default_storage.listdir(folder)[1]:
            name = f'{folder}/{file}'
            changed = default_storage.get_modified_time(name)
            if name not in named and changed < older_than:
                yield name


class Command(BaseCommand):
    """List or delete stored files that no row names."""

    help = 'Delete stored pictures that no row names.'

    def add_arguments(self, parser):
        """Declare --dry-run."""
        parser.add_argument(
            '--dry-run', action='store_true',
            help='List the files, and delete nothing.',
        )

    def handle(self, *args, dry_run=False, **options):
        """List or delete each stray, then count them."""
        hour_ago = timezone.now() - timedelta(hours=1)
        found = list(strays(hour_ago))
        for name in found:
            self.stdout.write(name)
            if not dry_run:
                default_storage.delete(name)
        verb = 'Would delete' if dry_run else 'Deleted'
        self.stdout.write(f'{verb} {len(found)} files.')

Files newer than an hour are kept: an upload in progress has written its file but not yet saved its row. The tests, in events/tests/test_cleanup.py, age two files by changing their modification time:

"""cleanup_media finds files no row names (Chapter 42)."""
import io
import os
import time

from django.core.files.storage import default_storage
from django.core.management import call_command
from django.test import TestCase

from config.helpers import TemporaryMedia, picture, save_event
from events.images import cleaned_image, replace


def aged(name):
    """Make a stored file look two hours old."""
    path = default_storage.path(name)
    then = time.time() - 2 * 60 * 60
    os.utime(path, (then, then))


def cleanup(*args):
    """Run cleanup_media; return its output lines."""
    out = io.StringIO()
    call_command('cleanup_media', *args, stdout=out)
    return out.getvalue().splitlines()


class CleanupTests(TemporaryMedia, TestCase):
    """Only old files that no row names are deleted."""

    def setUp(self):
        super().setUp()
        self.event = save_event()
        replace(self.event, 'cover', cleaned_image(picture()))
        self.stray = default_storage.save(
            'covers/left.jpg', cleaned_image(picture()))
        aged(self.event.cover.name)
        aged(self.stray)
        self.new = default_storage.save(
            'covers/new.jpg', cleaned_image(picture()))

    def test_a_dry_run_lists_and_keeps(self):
        lines = cleanup('--dry-run')
        self.assertEqual(lines, ['covers/left.jpg',
                                 'Would delete 1 files.'])
        self.assertTrue(default_storage.exists(self.stray))

    def test_strays_are_deleted_and_the_rest_kept(self):
        self.assertEqual(cleanup()[-1], 'Deleted 1 files.')
        self.assertFalse(default_storage.exists(self.stray))
        self.assertTrue(default_storage.exists(
            self.event.cover.name))
        self.assertTrue(default_storage.exists(self.new))
uv run python manage.py test events.tests.test_cleanup
uv run python manage.py cleanup_media --dry-run
Found 2 test(s).
Creating test database for alias 'default'...
...
Ran 2 tests in ...s

OK
Would delete 0 files.

Your media/ folder does not exist yet, so there is nothing to delete. Run the dry run first, every time, and read the list before deleting.

Step 11: Members’ photos

Initials stand in for a missing photo. In events/models.py, above organizer_problem():

def initials(name):
    """Return up to two capital letters for a name."""
    words = name.split()[:2]
    return ''.join(word[0] for word in words).upper()

In accounts/views.py, below the Django imports:

from events.forms import PictureForm
from events.images import replace
from events.models import initials

add 'initials': initials(user.display_name), as the first item ProfileView.get_context_data() returns, and at the end:

class ProfilePhotoView(FormView):
    """Add, change, or remove the member's own photo."""

    form_class = PictureForm
    template_name = 'accounts/photo.html'
    http_method_names = ['get', 'post']

    def get_context_data(self, **kwargs):
        """Add the profile, for the current photo."""
        return super().get_context_data(**kwargs) | {
            'profile': Profile.of(self.request.user),
        }

    def post(self, request, *args, **kwargs):
        """Remove the photo, or check and save a new one."""
        if request.POST.get('action') == 'remove':
            replace(Profile.of(request.user), 'photo', None)
            messages.success(request, 'Photo removed.')
            return redirect('accounts:profile')
        return super().post(request, *args, **kwargs)

    def form_valid(self, form):
        """Save Otahque's copy; the old file goes after."""
        replace(Profile.of(self.request.user), 'photo',
                form.cleaned_data['image'])
        messages.success(self.request, 'Photo saved.')
        return redirect('accounts:profile')

FormView passes request.FILES to the form for a POST itself. The view reads no id from the address: a member can only ever change their own photo. In accounts/urls.py:

    path('accounts/profile/photo/',
         views.ProfilePhotoView.as_view(), name='photo'),

The page, accounts/templates/accounts/photo.html:

{% extends "base.html" %}

{% block title %}Your photo | Otahque{% endblock %}

{% block content %}
  <h1>Your photo</h1>
  <p>Your photo is shown beside your name on the pages of
     events you organize, so anyone who can see those pages
     can see it. Otherwise only you can.</p>
  <section class="card space-y-4 border border-base-300
                  bg-base-100 p-6">
    {% if profile.photo %}
      <img class="avatar avatar-large"
           src="{{ profile.photo.url }}"
           alt="Your current photo">
    {% else %}
      <p class="text-sm">No photo yet: your initials are
         shown instead.</p>
    {% endif %}
    <form method="post" enctype="multipart/form-data"
          class="space-y-4">
      {% csrf_token %}
      {{ form }}
      <div class="form-actions">
        <button type="submit" class="btn btn-primary">
          Save photo</button>
      </div>
    </form>
    {% if profile.photo %}
      <form method="post">
        {% csrf_token %}
        <button type="submit" name="action" value="remove"
                class="btn btn-outline">Remove photo</button>
      </form>
    {% endif %}
  </section>
  <p><a href="{% url 'accounts:profile' %}">
    Back to your profile</a></p>
{% endblock %}

and on the profile page, accounts/templates/accounts/profile.html, above {% if missing %}:

  {# Chapter 42: the photo shown on events they organize. #}
  <section class="photo-card" aria-labelledby="photo">
    {% if user.profile.photo %}
      <img class="avatar avatar-large"
           src="{{ user.profile.photo.url }}" alt="">
    {% else %}
      <span class="avatar avatar-large avatar-initials"
            aria-hidden="true">{{ initials }}</span>
    {% endif %}
    <div>
      <h2 id="photo">Your photo</h2>
      <a href="{% url 'accounts:photo' %}" class="btn btn-sm">
        {% if user.profile.photo %}Change photo{% else %}
        Add a photo{% endif %}</a>
    </div>
  </section>

The tests, in accounts/tests/test_photos.py:

"""Members' photos, and organizers' photos on event pages.

Chapter 42. Files go to a temporary folder (TemporaryMedia).
"""
from django.test import TestCase
from django.urls import reverse

from accounts.models import Profile
from config.helpers import (
    TemporaryMedia, in_group, picture, save_event,
)
from events.models import Event

PHOTO = reverse('accounts:photo')


def fetch(client, address):
    """Get a stored file and read it all (see test_pictures)."""
    page = client.get(address)
    if page.streaming:
        b''.join(page.streaming_content)
    return page


class PhotoTests(TemporaryMedia, TestCase):
    """A member's photo is theirs, and their events' pages'."""

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

    def setUp(self):
        super().setUp()
        self.client.force_login(self.sam)
        self.client.post(PHOTO, {'image': picture()})
        self.photo = Profile.of(self.sam).photo

    def test_a_member_adds_a_photo(self):
        self.assertTrue(self.photo.name.startswith('photos/'))
        page = self.client.get(reverse('accounts:profile'))
        self.assertContains(page, self.photo.url)

    def test_only_its_owner_sees_it_at_first(self):
        address = self.photo.url
        self.assertEqual(fetch(self.client, address).status_code,
                         200)
        self.client.force_login(self.raj)
        self.assertEqual(fetch(self.client, address).status_code,
                         404)

    def test_it_is_public_once_they_organize_an_event(self):
        save_event().add_organizer(self.sam)
        self.client.logout()
        page = fetch(self.client, self.photo.url)
        self.assertEqual(page.status_code, 200)

    def test_a_drafts_organizer_stays_private(self):
        draft = save_event(status=Event.Status.DRAFT)
        draft.add_organizer(self.sam)
        self.client.logout()
        page = fetch(self.client, self.photo.url)
        self.assertEqual(page.status_code, 404)

    def test_a_member_removes_their_photo(self):
        with self.captureOnCommitCallbacks(execute=True):
            self.client.post(PHOTO, {'action': 'remove'})
        self.assertEqual(Profile.of(self.sam).photo.name, '')
        self.assertFalse(self.photo.storage.exists(
            self.photo.name))
uv run python manage.py test accounts.tests.test_photos
Found 5 test(s).
Creating test database for alias 'default'...
...
Ran 5 tests in ...s

OK

Step 12: The event page shows its pictures

In events/templates/events/detail.html, as the first thing inside <article>:

    {% if event.cover %}
      {# Decorative: the title below says what it is. #}
      <img class="event-cover" src="{{ event.cover.url }}"
           alt="">
    {% endif %}

and below {% include "events/facts.html" %}, add {% include "events/gallery.html" %}. The gallery, events/templates/events/gallery.html:

{# The event's gallery (Chapter 42): a grid of photos. #}
{# Each opens larger in a popover, with no JavaScript. #}
{% if photos %}
  <section class="space-y-3" aria-labelledby="gallery">
    <h2 id="gallery" class="text-lg font-semibold">Photos</h2>
    <ul class="gallery-grid">
      {% for photo in photos %}
        <li>
          <button type="button" class="gallery-thumb"
                  popovertarget="photo-{{ photo.pk }}">
            <img src="{{ photo.image.url }}"
                 alt="{{ photo.alt_text }}" loading="lazy">
          </button>
          <div id="photo-{{ photo.pk }}" popover
               class="gallery-viewer">
            <img src="{{ photo.image.url }}"
                 alt="{{ photo.alt_text }}">
            <p>{{ photo.alt_text }}</p>
            <button type="button" class="btn btn-sm"
                    popovertarget="photo-{{ photo.pk }}"
                    popovertargetaction="hide">Close</button>
          </div>
        </li>
      {% endfor %}
    </ul>
  </section>
{% endif %}

Each thumbnail is a button with popovertarget, and each larger photo a popover element: the browser opens and closes it, closes it with Escape, and returns focus to the button, with no JavaScript (Baseline since 2024). The cover’s alt="" marks it decorative, because the title below says what the page is; the gallery’s photos carry their descriptions. EventDetailView.get_context_data() adds the photos:

        """Add the time, edit link, photos, and the panel."""
        now = timezone.now()
        user = self.request.user
        return super().get_context_data(**kwargs) | {
            'now': now,
            'can_edit': self.object.can_be_edited_by(user),
            'photos': self.object.photos.all(),

The test, in a new file events/tests/test_event_page.py:

"""What an event's page shows of its pictures (Chapter 42)."""
from django.core.files.storage import default_storage
from django.test import TestCase

from config.helpers import TemporaryMedia, in_group, picture
from events.images import cleaned_image, replace
from events.tests.test_pictures import fetch
from registrations.tests.test_registrations import soon


class PicturesOnThePageTests(TemporaryMedia, TestCase):
    """The cover and the gallery, seen by a visitor."""

    def test_the_cover_and_gallery_are_shown(self):
        event = soon()
        replace(event, 'cover', cleaned_image(picture()))
        photo = event.add_photo(cleaned_image(picture()),
                                'Sam at the whiteboard')
        page = self.client.get(event.get_absolute_url())
        self.assertContains(page, event.cover.url)
        # Twice: the thumbnail, and the larger one it opens.
        self.assertContains(page, 'alt="Sam at the whiteboard"',
                            count=2)
        file = fetch(self.client, photo.image.url)
        self.assertEqual(file.status_code, 200)
        self.assertTrue(default_storage.exists(photo.image.name))

Run it with the rest of the events app’s tests:

uv run python manage.py test events
Found 246 test(s).
Creating test database for alias 'default'...
FAIL: test_pages_show_places_left
AssertionError: 4 != 3 : 4 queries executed, 3 expected
Ran 246 tests in ...s

FAILED (failures=1)

An earlier test counts the event page’s queries, and the gallery is one more. The count is the test’s point, so it changes on purpose. In events/tests/test_events.py, in test_pages_show_places_left:

        # The registration panel counts places again, and
        # the gallery is read (Chapter 42).
        with self.assertNumQueries(4):
            response = self.client.get(
uv run python manage.py test events
Found 246 test(s).
Creating test database for alias 'default'...
...
Ran 246 tests in ...s

OK

Step 13: Organized by, with photos

Chapter 27 put organizers’ names on public event pages; now a small photo, or initials, goes beside each (D42.7). In events/models.py, add from django.core.files.storage import default_storage to the imports, and in Event, above organizer_names():

    def organizer_people(self):
        """List current organizers: name, photo, initials."""
        rows = self.organizer_assignments.filter(
            revoked_at__isnull=True
        ).values_list('member__display_name',
                      'member__profile__photo')
        return [{
            'name': name,
            'photo': default_storage.url(photo) if photo else '',
            'initials': initials(name),
        } for name, photo in rows]

One query reads each organizer’s name and photo, through the profile; a member who has never opened their profile has no Profile row, and the join gives None. The round picture, templates/includes/avatar.html:

{# A member's round photo, or their initials (Chapter 42). #}
{# The name is printed beside it, so the image adds no #}
{# information: its alt text is empty. #}
{% if person.photo %}
  <img class="avatar" src="{{ person.photo }}" alt=""
       width="40" height="40" loading="lazy">
{% else %}
  <span class="avatar avatar-initials" aria-hidden="true">
    {{ person.initials }}</span>
{% endif %}

In events/templates/events/detail.html, the “Organized by” block becomes:

      {% with people=event.organizer_people %}
        {% if people %}
          <div class="organized-by">
            <span class="text-sm">Organized by</span>
            <ul>
              {% for person in people %}
                <li>{% include "includes/avatar.html" %}
                  {{ person.name }}</li>
              {% endfor %}
            </ul>
          </div>
        {% endif %}
      {% endwith %}

and a test, at the end of events/tests/test_event_page.py:

class OrganizedByTests(TestCase):
    """Organizers are shown with a photo, or initials."""

    def test_initials_stand_in_for_a_missing_photo(self):
        sai = in_group('sai.kumar@example.org', 'Organizers')
        sai.display_name = 'Sai Kumar'
        sai.save()
        event = soon()
        event.add_organizer(sai)
        page = self.client.get(event.get_absolute_url())
        self.assertContains(page, 'Organized by')
        self.assertContains(page, 'SK</span>')
        self.assertContains(page, 'Sai Kumar</li>')
uv run python manage.py test events
Found 247 test(s).
Creating test database for alias 'default'...
FAIL: test_the_name_follows_the_profile
AssertionError: False is not true : Couldn't find 'Organized
    by Sam Chen' in the following response
FAIL: test_the_organizer_is_named
AssertionError: False is not true : Couldn't find 'Organized
    by Sam' in the following response
Ran 247 tests in ...s

FAILED (failures=2)

The earlier tests looked for “Organized by Sam” as one string; each name is now a list item after its photo. They change on purpose, to look for the name as a list item. In events/tests/test_events.py, in OrganizedByTests:

    # Chapter 42: each name is a list item, after a photo.
    def test_the_organizer_is_named(self):
        page = self.page()
        self.assertContains(page, 'Organized by')
        self.assertContains(page, 'Sam</li>')

    def test_the_name_follows_the_profile(self):
        self.sam.display_name = 'Sam Chen'
        self.sam.save()
        page = self.page()
        self.assertContains(page, 'Sam Chen</li>')
uv run python manage.py test events
Found 247 test(s).
Creating test database for alias 'default'...
...
Ran 247 tests in ...s

OK

Step 14: Covers on cards, styles, and records

On the event list, events/templates/events/list.html, as the first thing inside each card:

            {% if event.cover %}
              <img class="card-cover" src="{{ event.cover.url }}"
                   alt="" loading="lazy">
            {% endif %}

loading="lazy" lets the browser fetch a card’s cover only when it scrolls near. The styles, in static/otahque/source.css, above .form-actions:

  /* Pictures (Chapter 42): covers, round photos with
     initials, and the gallery with its popover viewer. */
  .event-cover {
    width: 100%;
    max-height: 20rem;
    object-fit: cover;
    border-radius: var(--radius-box);
  }
  .card-cover {
    width: calc(100% + 2rem);
    max-width: none;
    height: 8rem;
    margin: -1rem -1rem 0;
    object-fit: cover;
    border-radius: var(--radius-box) var(--radius-box) 0 0;
  }
  .cover-preview {
    width: 100%;
    max-height: 12rem;
    object-fit: cover;
    border-radius: var(--radius-box);
  }
  .avatar {
    display: inline-grid;
    place-items: center;
    width: 2.5rem;
    height: 2.5rem;
    flex: none;
    border-radius: 9999px;
    object-fit: cover;
  }
  .avatar-initials {
    background-color: var(--color-primary);
    color: var(--color-primary-content);
    font-size: 0.875rem;
    font-weight: 600;
  }
  .avatar-large {
    width: 4.5rem;
    height: 4.5rem;
    font-size: 1.375rem;
  }
  .organized-by {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 0.5rem 0.75rem;
  }
  .organized-by ul {
    display: flex;
    flex-wrap: wrap;
    gap: 0.5rem 1rem;
  }
  .organized-by li {
    display: flex;
    align-items: center;
    gap: 0.5rem;
  }
  .photo-card {
    display: flex;
    align-items: center;
    gap: 1rem;
    padding: 1rem 1.25rem;
    border: 1px solid var(--color-base-300);
    border-radius: var(--radius-box);
    background-color: var(--color-base-100);
  }
  .photo-card h2 {
    font-size: 1.0625rem;
    font-weight: 600;
  }
  .gallery-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill,
                                  minmax(7rem, 1fr));
    gap: 0.5rem;
  }
  .gallery-grid img {
    width: 100%;
    aspect-ratio: 1;
    object-fit: cover;
    border-radius: var(--radius-field);
  }
  .gallery-thumb {
    display: block;
    width: 100%;
    cursor: zoom-in;
  }
  .gallery-item {
    display: grid;
    gap: 0.25rem;
  }
  .gallery-viewer {
    /* Preflight sets every margin to 0; a popover centres
       itself with margin: auto. */
    margin: auto;
    max-width: min(90vw, 60rem);
    padding: 1rem;
    border-radius: var(--radius-box);
    background-color: var(--color-base-100);
  }
  .gallery-viewer::backdrop {
    background-color: rgb(0 0 0 / 0.7);
  }
  .gallery-viewer img {
    max-height: 75vh;
    margin-inline: auto;
  }
  .gallery-viewer p {
    margin-block: 0.5rem;
  }

The account pages’ classes must reach the stylesheet too: add @source "../../accounts/templates"; below the other @source lines. Then build:

npm run build

The result, on a phone and on a desktop, is in Figure 42.4.

Two screenshots of the Sample clinic page, signed out. Left, at 390 pixels: a cover across the top, the title, Organized by with a round photo and the name Sam, the description, the facts, and Photos, a grid of three photos two to a row, then the registration panel. Right, at 1280 pixels: the same, with the registration panel to the right and the three photos in one row.
Figure 42.4 — An event page with its cover, organizer photo, and gallery.

Record the rules in a new design note, docs/design/uploads.md, which also lists threats for Chapter 59:

# Uploaded pictures (Chapter 42)

Status: proposed for review. Decisions D42.1-D42.7, N42.8,
N42.9 (DECISIONS.md).

## What can be uploaded

- Cover (Event.cover): uploaded by the event's
  organizers; seen like the event page.
- Gallery photo (EventPhoto.image): the same.
- Member photo (Profile.photo): uploaded by the member;
  seen by them, and by anyone who may see an event they
  organize.

At most 12 gallery photos per event, counted under the
event's lock; each needs a description (its alt text).
A copied event gets its own copy of the cover, and no
gallery.

## Checks, in order (events/images.py)

1. At most 5 MB (a validator; the web server's own limit
   is Chapter 63's).
2. Open the header only; refuse more pixels than Pillow's
   Image.MAX_IMAGE_PIXELS, before any pixel is decoded.
3. JPEG, PNG, or WebP only; SVG and GIF refused.
4. verify(), then decode, turn by EXIF orientation, and
   shrink to at most 1600 pixels.
5. Save a new copy: PNG if see-through, else JPEG. No
   metadata survives, so no GPS position.
6. A random name: covers/, gallery/, or photos/, then 32
   hexadecimal characters.

## Serving

Every file goes through config.views.media, which finds
the row that names the file and applies that row's rule.
A file no row names, and a file the viewer may not see,
are both 404. Public files may be cached for an hour;
private ones are checked again each time. MEDIA_URL is
never served directly.

## Deleting

A replaced or removed file is deleted after the change
commits; a rolled-back change keeps it. cleanup_media
deletes files no row names, older than an hour, with
--dry-run to list them first.

## Threat notes for Chapter 59

- A picture is untrusted input: decoding is the risky
  step, so the size and pixel checks come first.
- Pillow is a native library: keep it updated (its
  security releases), and pin it.
- Stored names never come from the member's file name.
- A file served from Otahque's own domain could run as a
  page if it were HTML; only re-encoded pictures are
  stored, and nosniff is sent.
- Members' photos are personal data: retention and
  deletion of an account's files are Chapter 65's.
- Not handled yet: malware scanning, a web server size
  limit (63), object storage with private buckets (63),
  attendee photos after an event, moderated (72).

In docs/design/erd.md, below the Chapter 41 lines:

Chapter 42 adds, for review:
- Event.cover and Profile.photo: pictures, optional.
- EventPhoto: event, image, alt_text, position,
  added_at; at most 12 per event (D42.1).

and at the end of docs/design/permissions.md:

## Pictures (Chapter 42)

The pictures page and photo removal answer as the edit
page does: the event's organizers who may change events;
others 403, recorded, or 404 for a hidden draft. The
media view is public under login by default and decides
each file by its row's rule (docs/design/uploads.md).

Step 15: 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 508 test(s).
System check identified no issues (0 silenced).
Ran 508 tests in ...s
OK
== all checks passed
git add .
git status --short
git commit -m "Add covers, a gallery, and member photos"
M  .gitignore
A  accounts/migrations/0007_photo.py
M  accounts/models.py
A  accounts/templates/accounts/photo.html
M  accounts/templates/accounts/profile.html
A  accounts/tests/test_photos.py
M  accounts/urls.py
M  accounts/views.py
M  config/helpers.py
M  config/settings.py
M  config/tests/test_public.py
M  config/urls.py
M  config/views.py
M  docs/design/erd.md
M  docs/design/permissions.md
A  docs/design/uploads.md
M  events/forms.py
A  events/images.py
A  events/management/commands/cleanup_media.py
A  events/migrations/0010_pictures.py
M  events/models.py
M  events/templates/events/detail.html
A  events/templates/events/gallery.html
M  events/templates/events/list.html
A  events/templates/events/pictures.html
A  events/tests/test_cleanup.py
A  events/tests/test_copies.py
A  events/tests/test_event_page.py
M  events/tests/test_events.py
A  events/tests/test_images.py
A  events/tests/test_pictures.py
M  events/urls.py
M  events/views.py
M  pyproject.toml
M  static/otahque/site.css
M  static/otahque/source.css
A  templates/django/forms/widgets/file.html
A  templates/includes/avatar.html
M  uv.lock
[main 1a2b3c4] Add covers, a gallery, and member photos
 39 files changed, 1901 insertions(+), 18 deletions(-)
 create mode 100644 accounts/migrations/0007_photo.py
 create mode 100644 accounts/templates/accounts/photo.html
 create mode 100644 accounts/tests/test_photos.py
 create mode 100644 docs/design/uploads.md
 create mode 100644 events/images.py
 create mode 100644
    events/management/commands/cleanup_media.py
 create mode 100644 events/migrations/0010_pictures.py
 create mode 100644 events/templates/events/gallery.html
 create mode 100644 events/templates/events/pictures.html
 create mode 100644 events/tests/test_cleanup.py
 create mode 100644 events/tests/test_copies.py
 create mode 100644 events/tests/test_event_page.py
 create mode 100644 events/tests/test_images.py
 create mode 100644 events/tests/test_pictures.py
 create mode 100644 templates/django/forms/widgets/file.html
 create mode 100644 templates/includes/avatar.html

If something goes wrong

Table 42.2 — Recovery for Chapter 42
What you see Likely cause What to do
uv add: no network, or the package not found Offline, or a typing mistake in the version Connect, check pillow==13.0.0, and run it again
No module named 'PIL' uv add did not finish Run uv sync, then the tests again
The form says the picture is required although you chose one The form has no enctype, or the view does not pass request.FILES Compare with pictures.html and event_pictures()
A picture shows as a broken image Its address is not under /media/, or the media URL line is missing Check MEDIA_URL and config/urls.py; open the address to see the 404
Tests leave files in media/ A test class without TemporaryMedia, or a setUp() that skips super().setUp() Add the mixin first; call super().setUp() first
PermissionError when a test ends, on Windows A FileResponse left open Use fetch(), which reads it to the end
the connection is closed, in later tests response.close() called in a test Read the response with fetch() instead
A draft's cover loads for a visitor The view used MEDIA_URL directly, or may_see() was changed Rerun events.tests.test_pictures; compare may_see()
PAGE 003

Verify Your Work

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

Table 42.3 — Verification checklist for Chapter 42
Check Command or action Expected result
Starting point test --parallel Found 475 test(s); OK
Pillow uv add pillow==13.0.0 + pillow==13.0.0; pinned in pyproject.toml
Checks test events.tests.test_images Red; then 9 tests OK
Migrations makemigrations, then migrate events 0010 and accounts 0007 applied
Media view test config.tests.test_public Red; then 3 tests OK
Pictures page test events.tests.test_pictures Found 14 test(s); OK
Copies test events.tests.test_copies Red; then 1 test OK
Cleanup test events.tests.test_cleanup; cleanup_media --dry-run 2 tests OK; Would delete 0 files.
Photos test accounts.tests.test_photos Found 5 test(s); OK
Event page test events.tests.test_event_page events.tests.test_events Red twice, each fixed on purpose; then OK
UI Event page, list, pictures page, and profile at 390 and 1280 px Cover, round photo or initials, gallery opening larger; no sideways scroll
All checks uv run python check.py == all checks passed; Ran 508 tests
Commit git log --oneline -1 Add covers, a gallery, and member photos
Not verified macOS and Linux shells; browsers other than Edge; HEIC photos from iPhones Pillow 13 does not read HEIC; such a photo is refused as not a picture

The commands were checked in Windows PowerShell 5.1 and Git Bash, from a copy of the Chapter 41 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, its pictures, and a photo for Sam added for the screenshots only and deleted afterwards, files and records included.

PAGE 004

Checkpoint: Quiz and Challenge

Quiz

Que. 1 Why does Otahque check a picture’s pixel count before decoding it, when Pillow has its own limit?

Flip to check your answerFold answer back

Answer. Decoding is what uses the memory, so the check must come first. Pillow’s limit only warns between MAX_IMAGE_PIXELS and twice that number, and decodes anyway; opened() turns the warning into a refusal while reading only the header.

Que. 2 What does re-encoding remove that validation alone would keep?

Flip to check your answerFold answer back

Answer. Everything that is not pixels: EXIF metadata such as the GPS position and camera details, and any extra bytes hidden in the file. The stored file is one Otahque wrote, in JPEG or PNG.

Que. 3 Why is the media view marked login_not_required, and why is that safe?

Flip to check your answerFold answer back

Answer. A published event’s cover must load for visitors, and login is required by default. It is safe because the view decides each file itself, by the owning row’s rule, and answers 404 for anything the viewer may not see.

Que. 4 When Sam replaces a cover, when is the old file deleted, and why then?

Flip to check your answerFold answer back

Answer. After the transaction commits, through transaction.on_commit(). If the save failed and rolled back, the row would still name the old file, so it must still exist.

Que. 5 Why is the upload field a forms.FileField rather than forms.ImageField?

Flip to check your answerFold answer back

Answer. forms.ImageField opens and verifies the file itself, during field cleaning, before Otahque’s clean_image() runs, so a decompression bomb would be decoded first. A FileField leaves all of it to cleaned_image().

Mini-Challenge

WebP is allowed, but Otahque stores JPEG or PNG. Write a test, in events/tests/test_webp.py, that a WebP photo is accepted and kept as a JPEG named picture.jpg.

Hint: picture() takes kind='WEBP'; open the returned content with Pillow and read its format.

Model answer:

"""A WebP picture is kept as a JPEG (Chapter 42 challenge)."""
import io

from django.test import SimpleTestCase
from PIL import Image

from config.helpers import picture
from events.images import cleaned_image


class WebpTests(SimpleTestCase):
    """WebP is allowed; Otahque's copy is a JPEG."""

    def test_a_webp_photo_becomes_a_jpeg(self):
        upload = picture('photo.webp', kind='WEBP')
        content = cleaned_image(upload)
        self.assertEqual(content.name, 'picture.jpg')
        kept = Image.open(io.BytesIO(content.read()))
        self.assertEqual(kept.format, 'JPEG')
Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...s

OK

The model answer was run and then removed; the chapter’s checkpoint does not include it.

What We Learned

  • A form sends files only with enctype="multipart/form-data"; Django puts them in request.FILES.
  • FILE_UPLOAD_MAX_MEMORY_SIZE decides where an upload waits, not how large it may be.
  • A picture is checked by its content: size, pixel count before decoding, and format, then re-encoded so no metadata survives.
  • FileField and ImageField store a name; the bytes go to the storage in STORAGES, under a random name.
  • Serve stored files through a view that asks the owning row who may see each one; never serve MEDIA_ROOT directly.
  • Delete a replaced file after commit; clean up files no row names with a dry run first.
  • Tests that upload use a temporary MEDIA_ROOT, and close every FileResponse.

Key terms

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

Table 42.4 — Key terms from Chapter 42
Term Meaning
request.FILES The uploaded files of a request, by field name.
enctype The form attribute that makes a browser send files.
UploadedFile One uploaded file: name, size, and bytes.
Storage Where file bytes are kept; configured in STORAGES.
MEDIA_ROOT, MEDIA_URL The folder for stored files, and their address prefix.
Pillow The Python imaging library Django's ImageField uses.
Decompression bomb A small file that declares a huge picture.
EXIF Metadata inside a photo, such as its GPS position.
Re-encoding Writing a new file from a picture's pixels alone.
FileResponse A response that streams a file.

Readiness checkpoint: you are ready for Chapter 43 when uv run python check.py ends with “all checks passed” and 508 tests, Sam can give the clinic a cover and three described photos, a visitor sees them once it is published but not before, your profile shows your photo or your initials, and git log --oneline -1 shows this chapter’s commit.

Git Commit

Your Chapter 42 work was committed once, in Step 15, as “Add covers, a gallery, and member photos”: Pillow, the settings, events/images.py, the fields, the gallery model and both migrations, the media view and its URL, the pictures and photo pages, the command, the templates and styles, the tests, and the design notes. Your own uploads stay out of Git, in media/. If you kept the Mini-Challenge, commit it on its own:

git add events/tests/test_webp.py
git commit -m "Check that a WebP photo is kept as a JPEG"
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 lost picture and to defending a design choice. 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 are files in request.FILES, not request.POST?

What the interviewer is testing: Do you know how a browser sends a file?

Flip to check your answerFold answer back

Perfect answer: A normal form is sent as one line of name=value pairs, which cannot carry a file’s bytes. With enctype="multipart/form-data" the browser sends each field as its own part, and a file part carries its name, its type, and its bytes. Django parses the parts, keeps text fields in request.POST, and puts each file in request.FILES as an UploadedFile, in memory or in a temporary file depending on its size. Without the enctype, the browser sends only the file’s name, as text, and request.FILES is empty.

Table 42.5 — One form, two encodings
Question Without enctype With multipart/form-data
What the browser sends name=photo.jpg The file's bytes in their own part
request.POST image: the name No image
request.FILES Empty image: an UploadedFile

Behind the scenes:

Content-Type: multipart/form-data; boundary=XyZ
--XyZ
Content-Disposition: form-data; name="image";
  filename="photo.jpg"
(the picture's bytes)
--XyZ--

Code proof: the same field sent both ways, with Django’s RequestFactory:

multipart: [] ['image']
no enctype: ['image'] []

Common mistakes:

  • Building a form with form = Form(request.POST) and forgetting request.FILES.
  • Reading request.FILES in a GET handler; files arrive only in a POST.

Follow-up the interviewer might ask:

  • Where does a 50 MB upload wait? (In a temporary file, because it is over FILE_UPLOAD_MAX_MEMORY_SIZE.)
  • Can a JSON API take files? (Not in JSON itself; it uses multipart, or a separate upload address.)

L2 (Mid-Level): Predict what happens when Sai uploads an SVG logo

What the interviewer is testing: Can you predict how a validator treats a format it was not written for?

Flip to check your answerFold answer back

Perfect answer: It is refused with “Choose a JPEG, PNG, or WebP picture.” An SVG is a text file, an XML drawing, so Pillow cannot identify it as a picture and opened() refuses it. That is what we want: an SVG can hold <script>, and served from Otahque’s own address it could run in a visitor’s browser with Otahque’s cookies. If Otahque ever needs vector logos, they would need their own sanitizer, a separate address, or a conversion to PNG, which is a decision for Chapter 59’s threat model, not a quick change to the allowed list.

A numbered flow of five cards. 1, an SVG drawing, logo.svg. 2, Pillow cannot identify it as a picture. 3, refused: choose a JPEG, PNG, or WebP picture. 4, allowed, it could run script from Otahque’s address. 5, only re-encoded pictures are ever stored.
Figure 42.5 — An SVG upload, predicted.

Behind the scenes:

Image.open(svg)   -> UnidentifiedImageError
opened()          -> ValidationError(NOT_A_PICTURE)

Code proof: an SVG with a script, sent to cleaned_image():

refused: Choose a JPEG, PNG, or WebP picture.

Common mistakes:

  • Allowing by extension, so logo.svg renamed logo.png would pass.
  • Trusting the browser’s content_type, which the uploader controls.

Follow-up the interviewer might ask:

  • And a GIF? (Pillow reads it, but FORMATS does not allow it, so it is refused too.)
  • How would you allow PDFs? (Not as pictures: a separate field, its own checks, and served as a download, never inline.)

L3 (Senior): Defend serving files through a view instead of MEDIA_URL

What the interviewer is testing: Can you weigh access control against simplicity and speed?

Flip to check your answerFold answer back

Perfect answer: Serving MEDIA_ROOT directly makes every stored file public to anyone with its address, and addresses leak: in shared links, browser history, and logs. A draft’s cover would be visible before Sam publishes, and a member’s photo before they organize anything. One view applies the same rules as the pages, from the rows that own the files, so access to a file can never be wider than access to its page. The cost is a database query and Python for every picture, which public caching softens. When that cost matters, in Chapter 63, the view can keep deciding and hand the sending to the web server or to signed object-storage addresses.

A numbered flow of five cards. 1, MEDIA_URL served directly: any name works. 2, a draft’s cover can be guessed or shared. 3, one view asks the row’s own rule. 4, public files cached; private ones checked each time. 5, revisit with object storage at Chapter 63.
Figure 42.6 — Why one view serves every file.

Behind the scenes:

draft cover, organizer     200, private, no-cache
draft cover, visitor       404
published cover, visitor   200, public, max-age=3600

Code proof: the pictures tests:

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

OK

Common mistakes:

  • Answering 403 for a hidden file, which tells the viewer it exists.
  • Long-caching a private picture, so a browser keeps showing it after access ends.

Follow-up the interviewer might ask:

  • Do random names make direct serving safe? (No: they stop guessing, not sharing, and a name can never be taken back.)
  • How would object storage keep this rule? (Private bucket; the view checks, then redirects to a short-lived signed address.)

L4 (Staff): A cover vanished after a failed save. Diagnose it

What the interviewer is testing: Can you reason about files and transactions together?

Flip to check your answerFold answer back

Perfect answer: A missing cover with a row that still names it means the file was deleted while the change that replaced it did not happen. That is the order bug: code that deletes the old file, then saves the row, inside a transaction that then rolls back. The database undoes the save; nothing undoes the delete. I would look for any storage.delete() or FieldFile.delete() called before commit, and move it into transaction.on_commit(), as delete_later() does. The proof is a test that replaces the cover inside a transaction it rolls back, then checks that the old file still exists.

A numbered flow of five cards. 1, a cover vanished after a failed save. 2, the old file was deleted before commit. 3, rollback restored the old name, not the file. 4, delete in transaction.on_commit(). 5, a test rolls back and finds the file.
Figure 42.7 — Diagnosing a vanished cover.

Behind the scenes:

delete old, save row, ROLLBACK   -> row names nothing
save row, COMMIT, delete old     -> always consistent

Code proof: a replacement rolled back, on a demo event, in a temporary folder:

after the rollback: True True

Common mistakes:

  • Deleting in a post_save signal, which runs before commit.
  • Fixing it with try/except around the save, which misses a rollback later in the same transaction.

Follow-up the interviewer might ask:

  • What if the process dies after commit, before the delete? (The old file is a stray; cleanup_media removes it.)
  • And the opposite failure? (A new file written, then a rollback: a stray, harmless, found the same way.)

L5 (Lead): Defend re-encoding over validation alone

What the interviewer is testing: Can you defend a costlier design with its risks and limits?

Flip to check your answerFold answer back

Perfect answer: Validation answers yes or no about the uploader’s file, and a yes stores that file as it came: its GPS position, camera serial, any bytes appended after the picture, and whatever a future decoder bug might trip on. Re-encoding stores a file Otahque wrote from pixels only, in two formats it chose, at a size it chose, so the stored set is predictable. The cost is CPU time per upload, a small loss of quality, and losing data some people want, such as colour profiles. The pixel and size limits bound the CPU cost, and both losses are acceptable for event pictures. I would revisit for a photography community, where originals matter, by keeping the original privately and serving only the re-encoded copy.

A numbered flow of five cards. 1, validation says yes or no to the original. 2, yes keeps GPS, camera, and hidden bytes. 3, re-encoding keeps only pixels. 4, cost: CPU time and a little quality. 5, bound it: pixel and size limits first.
Figure 42.8 — Validation alone, or a new copy.

Behind the scenes:

validated original   pixels + EXIF + extra bytes
re-encoded copy      pixels

Code proof: a photo with GPS, before and after:

sent: 2 tags
kept: 0 tags

Common mistakes:

  • Re-encoding without applying the orientation first, so phone photos turn sideways.
  • Re-encoding before the pixel check, which decodes the bomb anyway.

Follow-up the interviewer might ask:

  • Would you re-encode in the request? (For pictures of this size, yes; for large or many files, in a task, Chapter 44.)
  • What about HEIC photos from iPhones? (Pillow 13 cannot read them; a plug-in could, after a review of its security record.)
PAGE 006