Chapter 40 · Signals, application lifecycle, and system checksCHAPTER 40
Complete six-part pre-release for review. No package and no migration. A new DJANGO_FROM_EMAIL setting; check --deploy names two settings to fix before a real deployment.
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
Signals, application lifecycle, and system checks
Stage 5: Growing the application (Chapters 35 to 46)
Prerequisites: Chapters 9 to 39, including the Chapter 39 project with its 436 passing tests, the member’s Profile made on first use by Profile.of() (Chapters 27 and 31), the admin’s address from DJANGO_ADMIN_URL (Chapter 23), times stored and shown in UTC by default (Chapter 28), and the .env file (Chapter 8)
What you’ll build: A view of what Django does between manage.py and the first request; a signal receiver that creates profiles, built the way many tutorials do, shown failing with loaddata and wherever else code makes a profile itself, and then removed; tests that prove a member has at most one profile however the account was made; three Otahque system checks with ids and hints, two of them run only with check --deploy; and a “Finish your profile” card on the profile page
Why This Matters
A tutorial Sam’s team is reading says: “Create the profile automatically with a post_save signal.” It sounds tidier than Otahque’s way, where a profile is made the first time something asks for it. Is the tutorial right, and if not, why do so many people do it?
Separately, Soni reviews a reader’s deployment and finds the admin still at /admin/, the first address anyone scanning for Django sites tries, and Otahque’s emails going out from webmaster@localhost, an address no one reads. Both were mistakes in the settings, and nothing said so. Django can check settings when it starts, and say exactly what is wrong and how to fix it, before a single member sees the site.
Both lessons are about the moments before and around a request that a beginner rarely looks at: how Django starts, what runs when, and how one piece of code can make another run without either mentioning the other.
By the end of the chapter, you will be able to:
list what Django does from manage.py to the first request, and where AppConfig.ready() fits;
connect a receiver to a signal, and read what the signal sends, including created and raw;
explain why a post_save receiver that creates rows breaks loaddata, and what else it couples;
decide between an explicit call and a signal, and defend the choice;
write system checks with stable ids and hints, register them, and test them;
separate ordinary checks from deploy checks, and say why a check that needs DEBUG off must be a deploy check.
Out of scope: Django’s own deployment checks in a real deployment (Chapter 63), signals that delete uploaded files (Chapter 42), and receivers for security events such as failed sign-ins (Chapter 65).
Every command, runserver, migrate, test, starts the same way, shown in Figure 40.1. manage.py names the settings module; Django reads the settings; django.setup() builds the app registry, loading each installed app’s configuration class and then each app’s models; and once every app is loaded, Django calls each app’s ready() method. Then, for most commands, the system checks run. Only after that does the server accept a request, build the middleware chain from Chapter 39, and load the URL configuration.
Figure 40.1 — What happens before the first request.
Under the Hood: why ready() and not the top of apps.py
While Django loads the apps, the models of later apps do not exist yet. Importing accounts.models at the top of apps.py runs during that loading, and fails with AppRegistryNotReady if the models import another app’s models. ready() is called only when every app is loaded, so code that needs models, or that must run once at startup, goes there, imported inside the method. In tests ready() may run more than once, so it must not do anything that breaks if repeated.
Signals
New Concept: signals
What problem exists? One piece of code needs to know when something happens in another piece of code it does not own: allauth signs a member up, and your code wants to react, without editing allauth.
What did people do before? Edited the other code, or wrapped it, or copied it.
What is it? A signal is a named event that code can send, with arguments, to every receiver connected to it. post_save is sent by Django after any model instance is saved, with the model class as sender, the instance, created (true for a new row), and raw (true when loaddata saves the row exactly as the fixture holds it). A receiver is any function with a matching signature, connected with signal.connect(receiver, sender=Model) or the @receiver decorator.
Why use it? The sender does not need to know who listens. That is its strength for code you do not own, and its cost for code you do.
Now let’s use it. Step 3 watches post_save fire; Step 4 builds the profile receiver.
The cost is that the coupling is invisible. A line that says User.objects.create_user(...) reads like “make a user”; with a receiver connected somewhere else, it also makes a profile, and anything else anyone has connected. Code that creates a profile itself, which is perfectly reasonable without the receiver, now creates a second one and fails. Figure 40.2, after Step 5, compares the two ways.
Table 40.1 — Creating a profile: two ways
Question
Explicit, Profile.of()
Signal, post_save
When is it made?
When something first needs it
Whenever any user is saved new
Can you see it at the call?
Yes
No: it is in a receiver elsewhere
During loaddata?
Never
Yes, unless the receiver checks raw
Code that creates a profile itself
Works
Fails: the profile already exists
System checks
New Concept: the system check framework
What problem exists? A setting can be wrong in a way Django cannot refuse to load, such as the admin at its default address in production. Nothing fails until something goes wrong for real.
What did people do before? A checklist, or an assert in settings that stopped the server with a bare traceback.
What is it? A system check is a function registered with @register() that returns a list of messages, empty when all is well. Each message has a level (Error, Warning, and others), a text, a hint, and an id such as otahque.E001. Django runs every registered check before runserver, migrate, and the tests, and on manage.py check; any Error stops the command. A check registered with deploy=True runs only on check --deploy.
Why use it? The message is specific, has a fix in its hint, and can be silenced by id with SILENCED_SYSTEM_CHECKS when a team decides it does not apply.
Now let’s use it. Step 7 writes three.
Django has dozens of its own. Chapter 39 met one, auth.E013, and Django 6.1 adds mail.E001, a deploy check that fires when the mail backend in MAILERS is a development one, such as the console backend Otahque uses on a laptop. Otahque adds only what Django cannot know: Table 40.2.
Table 40.2 — Otahque’s system checks
Id
When
Fires when
otahque.E001
Always
USE_TZ is off, or TIME_ZONE is not UTC
otahque.W002
--deploy
The admin is at admin/
otahque.W003
--deploy
Emails would come from webmaster@localhost
Why are the last two deploy checks? Because the tests always run with DEBUG off, and on a laptop the admin is at admin/ on purpose. A check that said “with DEBUG off, the admin must not be at admin/” would fire in every test run, and as an Error it would stop them all. Production settings are checked when you deploy, with check --deploy, which Chapter 63 makes part of every release. Figure 40.3, in Step 7, follows a check from its code to its output.
In practice: E001 is about what is shown, not stored
Situation. A reader in Leeds sets TIME_ZONE = 'Europe/London' so the admin shows local times.
Application. With USE_TZ = True, Django stores every time in UTC whatever TIME_ZONE says. But TIME_ZONE is the zone the admin shows (Chapter 23 turns off the member’s zone there), and the zone of commands and log lines. Otahque’s rule is that those are UTC, and each member chooses their own zone on their profile (Chapter 28).
Consideration. E001 is an error, not a warning, because a mix of zones in admin screens and logs makes incidents hard to read.
Start from Chapter 39, in the folder containing manage.py, with Otahque on PostgreSQL 18, 436 passing tests, and the work committed (the last commit is “Find each request by its reference”). No package and no migration is new. The new files are config/checks.py, config/tests/test_checks.py, accounts/tests/test_profiles.py, and docs/design/checks.md; accounts/apps.py gains a ready() method; config/settings.py, .env.example, the profile view, its template, and the stylesheet source change. accounts/signals.py is created in Step 4 and deleted in Step 5. The visible result: manage.py check --deploy names two settings to fix before a real deployment, and the profile page shows a “Finish your profile” card while facts an event may ask for are empty. The chapter’s commands were checked in Windows PowerShell 5.1 and Git Bash against PostgreSQL 18.
The Custom Way
Steps 4 and 5 build the profile receiver many tutorials recommend, run the whole suite against it, and read what breaks, before removing it and keeping the tests that would catch it coming back.
The Django Way
Step 1: Check the starting point
Terminal
uv run python manage.py test --parallel
Output
Found 436 test(s).
Creating test database for alias 'default'...
...
Ran 436 tests in ...s
OK
Terminal
git status --short
git log --oneline -1
Output
... Find each request by its reference
Step 2: The apps Django loads
Create practice_apps.py beside manage.py:
practice_apps.py
"""Practice: the apps Django loaded, in order.
Run it once, then delete it.
"""
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE',
'config.settings')
django.setup()
from django.apps import apps # noqa: E402
for config in apps.get_app_configs():
print(config.label, '->', type(config).__name__)
Delete practice_apps.py. The order is INSTALLED_APPS, and each line names the configuration class Django used: AccountsConfig is Otahque’s own, from accounts/apps.py; apps without their own class get Django’s plain AppConfig. Django calls ready() on each, in this order, after all of them are loaded.
Step 3: Watch a signal fire
Create practice_signal.py. It connects a receiver that only prints, makes a user and saves them again, then rolls the transaction back, so the database is unchanged:
practice_signal.py
"""Practice: watch post_save fire, then undo the save.
Run it once, then delete it.
"""
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE',
'config.settings')
django.setup()
from django.db import transaction # noqa: E402
from django.db.models.signals import post_save # noqa: E402
from accounts.models import User # noqa: E402
def show(sender, instance, created, raw, **kwargs):
"""Print what the signal sends."""
print('post_save from', sender.__name__, '|',
instance.email, '| created:', created,
'| raw:', raw)
post_save.connect(show, sender=User)
with transaction.atomic():
member = User.objects.create_user(
'practice@example.org', display_name='Practice')
member.display_name = 'Practice again'
member.save()
transaction.set_rollback(True)
print('rolled back; users with that email:',
User.objects.filter(email='practice@example.org').count())
Terminal
uv run python practice_signal.py
Output
post_save from User | practice@example.org | created: True |
raw: False
post_save from User | practice@example.org | created: False |
raw: False
rolled back; users with that email: 0
Delete practice_signal.py. post_save fired twice: once with created: True, once with created: False. raw is false both times; it is true only when loaddata saves a row.
Step 4: A profile for every user, by signal (the Custom Way)
First the tests that must hold whichever way profiles are made, in a new file accounts/tests/test_profiles.py: sign-up makes one; a user made in the shell has none until first use, and two calls to Profile.of() still make one; createsuperuser makes at most one; and a fixture of a member and their profile loads back as one profile.
accounts/tests/test_profiles.py
"""At most one profile per member, made on first use.
Chapter 40: Otahque makes a profile when something first
needs it (Profile.of), not with a signal. These tests are
the evidence that every way of making a user agrees.
"""
import io
import tempfile
from pathlib import Path
from django.core.cache import cache
from django.core.management import call_command
from django.test import TestCase
from accounts.models import Profile, User
from .test_accounts import signup_data
def profiles(email):
"""Count the profiles of the member with this email."""
return Profile.objects.filter(user__email=email).count()
class OneProfileTests(TestCase):
"""Sign-up, the shell, createsuperuser, and loaddata."""
def test_sign_up_makes_one(self):
cache.clear()
self.client.post('/accounts/signup/', signup_data())
self.assertEqual(profiles('sai@example.org'), 1)
def test_a_new_user_has_none_until_first_use(self):
raj = User.objects.create_user('raj@example.org',
display_name='Raj')
self.assertEqual(profiles('raj@example.org'), 0)
Profile.of(raj)
Profile.of(raj)
self.assertEqual(profiles('raj@example.org'), 1)
def test_createsuperuser_makes_at_most_one(self):
call_command('createsuperuser', interactive=False,
email='soni@example.org',
display_name='Soni', stdout=io.StringIO())
self.assertLessEqual(profiles('soni@example.org'), 1)
def test_loaddata_keeps_one(self):
sam = User.objects.create_user('sam@example.org',
display_name='Sam')
Profile.of(sam)
dumped = io.StringIO()
call_command('dumpdata', 'accounts.user',
'accounts.profile', stdout=dumped)
Profile.objects.all().delete()
User.objects.all().delete()
with tempfile.TemporaryDirectory() as folder:
fixture = Path(folder) / 'members.json'
fixture.write_text(dumped.getvalue(),
encoding='utf-8')
call_command('loaddata', fixture, verbosity=0)
self.assertEqual(profiles('sam@example.org'), 1)
Terminal
uv run python manage.py test accounts.tests.test_profiles
Output
Found 4 test(s).
Creating test database for alias 'default'...
...
Ran 4 tests in ...s
OK
They pass with Otahque’s lazy profiles. Now do what the tutorial says. Create accounts/signals.py:
accounts/signals.py
"""Practice (Chapter 40): a profile for each new user.
The Custom Way, by signal; removed again in Step 5.
"""
from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import Profile, User
@receiver(post_save, sender=User, dispatch_uid='make_profile')
def make_profile(sender, instance, created, **kwargs):
"""Create the profile of a user who was just created."""
if created:
Profile.objects.create(user=instance)
A receiver only receives once its module has been imported, and the place for that is ready(). accounts/apps.py becomes:
accounts/apps.py
"""Configuration Django reads to load the accounts app."""
from django.apps import AppConfig
class AccountsConfig(AppConfig):
"""The accounts app: members and how they sign in."""
name = 'accounts'
def ready(self):
"""Connect the practice receiver (Chapter 40)."""
from . import signals # noqa: F401
Run the whole suite:
Terminal
uv run python manage.py test --parallel
Output
Found 440 test(s).
Creating test database for alias 'default'...
ERROR: setUpClass
django.db.utils.IntegrityError: duplicate key value violates
unique constraint "accounts_profile_user_id_key"
ERROR: setUpClass
django.db.utils.IntegrityError: duplicate key value violates
unique constraint "accounts_profile_user_id_key"
ERROR: setUpClass
django.db.utils.IntegrityError: duplicate key value violates
unique constraint "accounts_profile_user_id_key"
ERROR: test_a_missing_phone_is_named
django.db.utils.IntegrityError: duplicate key value violates
unique constraint "accounts_profile_user_id_key"
... (5 more like these)
Ran 431 tests in ...s
FAILED (failures=3, errors=6)
Read the failures. test_loaddata_keeps_one fails with IntegrityError: loaddata saved Sam’s user row, the receiver made a profile for him, and then the fixture’s own profile row, for the same member, broke the rule of one profile per member. The others fail for the same reason in different clothes: tests and code from Chapters 27 to 38 that create a profile themselves, reasonably, now find one already there. And test_a_new_user_has_none_until_first_use fails because a profile now exists before anyone needs it.
The usual fix is the raw guard. accounts/signals.py becomes:
accounts/signals.py
"""Practice (Chapter 40): a profile for each new user.
The Custom Way, by signal; removed again in Step 5.
"""
from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import Profile, User
@receiver(post_save, sender=User, dispatch_uid='make_profile')
def make_profile(sender, instance, created, **kwargs):
"""Create the profile of a user who was just created."""
# loaddata saves rows as they are: raw=True.
if created and not kwargs['raw']:
Profile.objects.create(user=instance)
Terminal
uv run python manage.py test accounts.tests.test_profiles
Output
Found 4 test(s).
Creating test database for alias 'default'...
FAIL: test_a_new_user_has_none_until_first_use
AssertionError: 1 != 0
Ran 4 tests in ...s
FAILED (failures=1)
loaddata passes now. Every other failure remains, because they were never about fixtures: they are about a User.objects.create_user() call that does something its caller cannot see.
Step 5: Remove the receiver
Delete accounts/signals.py, and put accounts/apps.py back as it was:
accounts/apps.py
"""Configuration Django reads to load the accounts app."""
from django.apps import AppConfig
class AccountsConfig(AppConfig):
"""The accounts app: members and how they sign in."""
name = 'accounts'
Terminal
uv run python manage.py test --parallel
Output
Found 440 test(s).
Creating test database for alias 'default'...
...
Ran 440 tests in ...s
OK
Green, with the four new profile tests kept. They are the evidence: if anyone adds the receiver again, test_a_new_user_has_none_until_first_use and test_loaddata_keeps_one say so at once.
Figure 40.2 — An explicit call and a signal.
Common Error: a receiver that runs twice
A member receives two welcome emails. The receiver is connected twice, but not because connect() was called twice with the same function: Django keeps one connection per function. It happens when the module holding the receiver is imported under two names, such as signals and accounts.signals, which makes two function objects, or when a receiver is defined inside ready(), which tests may call more than once. Import receivers once, in ready(), and give each a dispatch_uid. Interview question L4 proves it.
Step 6: Where signals are right
Signals earn their cost when the sender is code you do not own. allauth sends signals for the moments a site may want to react to. List them with practice_allauth.py:
practice_allauth.py
"""Practice: the signals allauth sends, by name.
Run it once, then delete it.
"""
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE',
'config.settings')
django.setup()
from allauth.account import signals # noqa: E402
from django.dispatch import Signal # noqa: E402
for name in sorted(vars(signals)):
public = not name.startswith('_')
if public and isinstance(getattr(signals, name), Signal):
print(name)
Delete the file. user_signed_up would be the way to send Sai a welcome email the moment allauth creates her account, without editing allauth. Otahque has no such need yet, so it connects nothing (decision D40.2). Chapter 65 revisits these signals for security records, such as password_changed.
Step 7: Otahque’s system checks, test-first
The tests, in a new file config/tests/test_checks.py. Each check is called directly with the settings it judges, and the last test runs Django’s own check command, with and without --deploy:
config/tests/test_checks.py
"""Otahque's system checks, one test each (Chapter 40)."""
import io
from django.core.management import call_command
from django.test import SimpleTestCase, override_settings
from config import checks
def ids(messages):
"""Return the ids of a check's messages."""
return [message.id for message in messages]
class TimeZoneCheckTests(SimpleTestCase):
"""otahque.E001: aware times, UTC by default."""
def test_quiet_on_otahques_settings(self):
self.assertEqual(checks.check_time_zone(None), [])
@override_settings(TIME_ZONE='Asia/Kolkata')
def test_another_default_zone(self):
self.assertEqual(ids(checks.check_time_zone(None)),
['otahque.E001'])
@override_settings(USE_TZ=False)
def test_naive_times(self):
self.assertEqual(ids(checks.check_time_zone(None)),
['otahque.E001'])
class DeployCheckTests(SimpleTestCase):
"""otahque.W002 and W003 describe production settings."""
@override_settings(ADMIN_URL='admin/')
def test_the_default_admin_address(self):
self.assertEqual(ids(checks.check_admin_url(None)),
['otahque.W002'])
@override_settings(ADMIN_URL='staff-7f3k/')
def test_another_admin_address(self):
self.assertEqual(checks.check_admin_url(None), [])
@override_settings(DEFAULT_FROM_EMAIL='webmaster@localhost')
def test_djangos_from_address(self):
self.assertEqual(ids(checks.check_from_email(None)),
['otahque.W003'])
@override_settings(DEFAULT_FROM_EMAIL='hi@otahque.example')
def test_a_real_from_address(self):
self.assertEqual(checks.check_from_email(None), [])
@override_settings(ADMIN_URL='admin/',
DEFAULT_FROM_EMAIL='webmaster@localhost')
def test_they_run_only_with_deploy(self):
quiet, loud = io.StringIO(), io.StringIO()
call_command('check', '--tag', 'otahque',
stdout=quiet, stderr=quiet)
call_command('check', '--deploy', '--tag', 'otahque',
stdout=loud, stderr=loud)
self.assertIn('no issues', quiet.getvalue())
self.assertIn('otahque.W002', loud.getvalue())
self.assertIn('otahque.W003', loud.getvalue())
Terminal
uv run python manage.py test config.tests.test_checks
Output
Found 1 test(s).
Creating test database for alias 'default'...
ERROR: test_checks
ImportError: Failed to import test module: test_checks
Ran 1 test in ...s
FAILED (errors=1)
The checks, in a new file config/checks.py:
config/checks.py
"""Otahque's own system checks (Chapter 40).
Django runs every registered check before runserver,
migrate, and the tests, and on manage.py check. Checks
registered with deploy=True run only on check --deploy,
the command a release runs (Chapter 63): they describe
production settings, which a laptop and the tests do
not have.
"""
from django.conf import settings
from django.core.checks import Error, Warning, register
# Django's own default, from django/conf/global_settings.py.
DJANGO_FROM_EMAIL = 'webmaster@localhost'
@register('otahque')
def check_time_zone(app_configs, **kwargs):
"""Require aware times, shown in UTC by default."""
if settings.USE_TZ and settings.TIME_ZONE == 'UTC':
return []
return [Error(
'Otahque stores and, by default, shows times in UTC.',
hint="Set USE_TZ = True and TIME_ZONE = 'UTC'; each "
'member chooses their own zone (Chapter 28).',
id='otahque.E001',
)]
@register('otahque', deploy=True)
def check_admin_url(app_configs, **kwargs):
"""Warn when the admin is at the address everyone tries."""
if settings.ADMIN_URL != 'admin/':
return []
return [Warning(
'The admin is at /admin/, the first address an '
'attacker tries.',
hint='Set DJANGO_ADMIN_URL to a path that is hard to '
'guess (Chapter 23).',
id='otahque.W002',
)]
@register('otahque', deploy=True)
def check_from_email(app_configs, **kwargs):
"""Warn when emails would come from Django's default."""
if settings.DEFAULT_FROM_EMAIL != DJANGO_FROM_EMAIL:
return []
return [Warning(
f'Emails would be sent from {DJANGO_FROM_EMAIL}, '
'which nobody reads.',
hint='Set DJANGO_FROM_EMAIL to an address members can '
'reply to.',
id='otahque.W003',
)]
@register('otahque') adds the function to Django’s registry under the tag otahque, so check --tag otahque runs Otahque’s alone. The ids follow Django’s pattern: a prefix, a letter for the level, and a number that never changes meaning, so a team can silence otahque.W002 by name in SILENCED_SYSTEM_CHECKS if they decide it does not apply.
Terminal
uv run python manage.py test config.tests.test_checks
Output
Found 8 test(s).
Creating test database for alias 'default'...
...
Ran 8 tests in ...s
OK
Green, and misleading: the test module itself imports config.checks, and importing the module is what runs the @register lines. Django’s own commands import nothing of the kind. Ask Django directly:
Terminal
uv run python manage.py check --tag otahque
Output
CommandError: There is no system check with the "otahque"
tag.
When Django starts, nothing has imported config/checks.py, so the checks do not exist. Import it in ready(); accounts/apps.py becomes:
accounts/apps.py
"""Configuration Django reads to load the accounts app."""
from django.apps import AppConfig
class AccountsConfig(AppConfig):
"""The accounts app: members and how they sign in."""
name = 'accounts'
def ready(self):
"""Register Otahque's system checks (Chapter 40).
Django calls ready() once every app is loaded, so
importing here is safe; a check that is never
imported is never registered.
"""
from config import checks # noqa: F401
config is not an installed app, so the checks are registered by the first of Otahque’s apps, accounts.
Terminal
uv run python manage.py check --tag otahque
Output
System check identified no issues (0 silenced).
Figure 40.3 — A system check from code to output.
Common Error: a production check that stops the tests
Writing W002 as an ordinary check, “with DEBUG off, the admin must not be at admin/”, looks right and passes manage.py check on a laptop, where DEBUG is on. But manage.py test always runs with DEBUG off, so the check fires there; as an Error, it stops the whole run with SystemCheckError before a single test. Rules about production settings belong in deploy checks.
Step 8: Read the checks’ output
W003 needs a setting to judge. In config/settings.py, below MAILERS:
config/settings.py
# The address Otahque's emails come from. Empty or unset
# means Django's default, webmaster@localhost, which makes
# check --deploy warn (otahque.W003).
DEFAULT_FROM_EMAIL = (config('DJANGO_FROM_EMAIL', default='')
or 'webmaster@localhost')
and in .env.example, below DJANGO_SUPPORT_EMAIL:
.env.example
# The address emails come from; check --deploy warns while
# it is Django's default (Chapter 40).
DJANGO_FROM_EMAIL=
config(...) or treats an empty line in .env like a missing one, as DB_ENGINE does since Chapter 32. Now ask Django:
Terminal
uv run python manage.py check
uv run python manage.py check --deploy --tag otahque
Output
System check identified no issues (0 silenced).
System check identified some issues:
WARNINGS:
?: (otahque.W002) The admin is at /admin/, the first address
an attacker tries.
HINT: Set DJANGO_ADMIN_URL to a path that is hard to
guess (Chapter 23).
?: (otahque.W003) Emails would be sent from
webmaster@localhost, which nobody reads.
HINT: Set DJANGO_FROM_EMAIL to an address members can
reply to.
System check identified 2 issues (0 silenced).
The ordinary run is quiet. The deploy run, limited to Otahque’s tag, names both settings with their fixes. Without --tag, check --deploy also lists Django’s own deployment advice, including mail.E001 for the console mail backend and warnings about HTTPS settings; Chapter 63 works through all of them for a real server. Do not change your .env to silence them: on a laptop, these values are right.
Step 9: Finish your profile
A profile made on first use is often empty, and the details page of Chapter 38 then asks for facts one event at a time. The profile page can say so once. In accounts/views.py, below the imports:
accounts/views.py
# What events may ask for (Chapters 31 and 38), in order.
ASKED = [('phone', 'phone number'), ('company', 'company'),
('college', 'college'), ('website', 'website')]
and ProfileView.get_context_data() becomes:
accounts/views.py
def get_context_data(self, **kwargs):
"""Add the two-factor and email notes, and gaps."""
user = self.request.user
profile = Profile.of(user)
return super().get_context_data(**kwargs) | {
'missing': [label for name, label in ASKED
if not getattr(profile, name)],
'two_factor': Authenticator.objects.filter(
user=user, type=Authenticator.Type.TOTP,
).exists(),
'unconfirmed': EmailAddress.objects.filter(
user=user, verified=False,
).exists(),
}
In accounts/templates/accounts/profile.html, above the form:
accounts/templates/accounts/profile.html
{% if missing %}
{# Chapter 40: the profile is made on first use, often #}
{# empty; say what events may ask for. #}
<aside class="finish-card" aria-labelledby="finish">
<h2 id="finish">Finish your profile</h2>
<p>Events may ask for these, and yours are empty:
{{ missing|join:", " }}. Add them once here, and
you will not be asked each time you register.</p>
<a href="#id_phone" class="btn btn-sm">Fill them in</a>
</aside>
{% endif %}
The styles, in static/otahque/source.css, inside @layer components, above .form-actions:
static/otahque/source.css
/* Finish your profile (Chapter 40): a card above the
form, while a fact events may ask for is empty. */
.finish-card {
display: grid;
gap: 0.5rem;
justify-items: start;
padding: 1rem 1.25rem;
border: 1px solid var(--color-base-300);
border-left: 6px solid var(--color-info);
border-radius: var(--radius-box);
background-color: var(--color-base-100);
}
.finish-card h2 {
font-size: 1.0625rem;
font-weight: 600;
}
Terminal
npm run build
For a member whose company, college, and website are empty, the page looks like Figure 40.4.
Figure 40.4 — The profile page with the “Finish your profile” card.
Step 10: Records and commit
Create docs/design/checks.md:
docs/design/checks.md
# Otahque's system checks
Status: Drafted in Chapter 40, for review. Not approved.
Code: config/checks.py, registered in
AccountsConfig.ready(). Tests: config/tests/test_checks.py.
| Id | Level | When | Says |
|--------------|---------|-----------|--------------------------|
| otahque.E001 | Error | Always | USE_TZ on, TIME_ZONE UTC |
| otahque.W002 | Warning | --deploy | Admin at /admin/ |
| otahque.W003 | Warning | --deploy | From webmaster@localhost |
Django's own checks cover the rest: auth.E013 (the
order of LoginRequiredMiddleware, Chapter 39) and
mail.E001 (a development-only mail backend, --deploy).
A check that needs DEBUG off is a deploy check: tests
always run with DEBUG off, so an ordinary check would
stop every test run. Chapter 63 runs check --deploy
with production settings as part of every release.
## Profiles
A profile is made on first use, by Profile.of(), and
never by a signal (Chapter 27, confirmed in Chapter
40): a post_save receiver made loaddata fail with
IntegrityError and collided with every piece of code
that creates a profile itself.
Check and commit:
Terminal
uv run python check.py
Output
== python manage.py check
System check identified no issues (0 silenced).
== python manage.py makemigrations --check --dry-run
== python manage.py test --parallel
Found 448 test(s).
System check identified no issues (0 silenced).
Ran 448 tests in ...s
OK
== all checks passed
Terminal
git add .
git status --short
git commit -m "Warn about unsafe settings at startup"
Output
M .env.example
M accounts/apps.py
M accounts/templates/accounts/profile.html
A accounts/tests/test_profiles.py
M accounts/views.py
A config/checks.py
M config/settings.py
A config/tests/test_checks.py
A docs/design/checks.md
M static/otahque/site.css
M static/otahque/source.css
[main 1a2b3c4] Warn about unsafe settings at startup
11 files changed, 283 insertions(+), 9 deletions(-)
create mode 100644 accounts/tests/test_profiles.py
create mode 100644 config/checks.py
create mode 100644 config/tests/test_checks.py
create mode 100644 docs/design/checks.md
If something goes wrong
Table 40.3 — Recovery for Chapter 40
Symptom
Likely cause
Recovery
check --tag otahque: no system check with that tag
config/checks.py never imported
Import it in AccountsConfig.ready()
AppRegistryNotReady at startup
A model imported at the top of apps.py
Import inside ready()
Every test run stops with SystemCheckError
A production rule written as an ordinary check
Register it with deploy=True
loaddata: IntegrityError on accounts_profile
A post_save receiver creating profiles
Remove it; Step 5
Two welcome emails per sign-up
A receiver connected twice
Import once, in ready(); dispatch_uid
W003 although DJANGO_FROM_EMAIL is in .env
The line is empty
Give it an address, or leave the warning for the laptop
Work through Table 40.4 from the folder that holds manage.py.
Table 40.4 — Verification checklist for Chapter 40
Check
Command or action
Expected result
Starting point
test --parallel
Found 436 test(s); OK
Apps and a signal
practice_apps.py, practice_signal.py
The apps in order; post_save twice; nothing saved
Profile tests
test accounts.tests.test_profiles
Found 4 test(s); OK
The Custom Way
The receiver connected, then test --parallel
loaddata IntegrityError and other failures; the raw guard fixes only loaddata
Receiver removed
test --parallel
Found 440 test(s); OK
Checks
test config.tests.test_checks; check --tag otahque
Red; 8 tests OK; no such tag until ready(); then no issues
Output
check; check --deploy --tag otahque
No issues; then W002 and W003 with hints
UI
Profile page at 390 and 1280 px
The Finish your profile card; no sideways scroll
All checks
uv run python check.py
== all checks passed; Ran 448 tests
Commit
git log --oneline -1
Warn about unsafe settings at startup
Not verified
macOS and Linux shells; browsers other than Edge; check --deploy with production settings
Chapter 63
The commands were checked in Windows PowerShell 5.1 and Git Bash, from a copy of the Chapter 39 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 Sai’s company, college, and website emptied for the screenshots only and put back afterwards.
Que. 1 Why does Otahque register its checks in AccountsConfig.ready(), not at the top of apps.py or in urls.py?
Flip to check your answerFold answer back
Answer. A check exists only once its @register line has run, which means its module must be imported at startup. ready() runs once every app is loaded, so imports there are safe. The top of apps.py runs while apps are still loading, and urls.py is imported too late, or not at all, for check.
Que. 2 What do created and raw tell a post_save receiver?
Flip to check your answerFold answer back
Answer. created is true when the save inserted a new row. raw is true when loaddata saved the row exactly as the fixture holds it, without the usual save() logic.
Que. 3 A post_save receiver creates a profile for each new user. Why does loaddata of members and their profiles fail?
Flip to check your answerFold answer back
Answer. loaddata saves the user row, the receiver creates a profile for that user, and then the fixture’s own profile row for the same user breaks the one-profile-per-user rule: IntegrityError.
Que. 4 Why are W002 and W003 deploy checks?
Flip to check your answerFold answer back
Answer. They describe production settings. On a laptop the admin is at admin/ and emails come from Django’s default on purpose, and the tests always run with DEBUG off. As ordinary checks they would fire every day and, as errors, stop every test run.
Que. 5 How would a team that does not want W002 turn it off, and why is that better than deleting the check?
Flip to check your answerFold answer back
Answer. List 'otahque.W002' in SILENCED_SYSTEM_CHECKS. The decision is written in settings by its id, and every other check keeps running.
Mini-Challenge
A reader in London sets TIME_ZONE = 'Europe/London'. Write a test, in config/tests/test_london.py, that Otahque’s time-zone check refuses it, and explain in one sentence why a member in London still sees London times.
"""The time-zone check and London (Chapter 40)."""
from django.test import SimpleTestCase, override_settings
from config import checks
class LondonTests(SimpleTestCase):
"""Otahque's default zone is UTC, even for London."""
@override_settings(TIME_ZONE='Europe/London')
def test_london_is_not_utc(self):
messages = checks.check_time_zone(None)
self.assertEqual([m.id for m in messages],
['otahque.E001'])
Output
Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...s
OK
A member’s pages use the zone on their profile, or their browser’s, through Chapter 28’s middleware; TIME_ZONE is only the default, which Otahque keeps at UTC for the admin, commands, and logs. The model answer was run and then removed; the chapter’s checkpoint does not include it.
What We Learned
Django reads settings, loads every app and its models, calls each ready(), runs the system checks, and only then handles requests.
Code that must run once at startup, or needs models, goes in ready(), imported inside the method.
A signal calls every connected receiver with what the sender sends; post_save sends created and raw.
A receiver that creates rows makes every save do more than it says: loaddata fails, and code that creates the same rows collides.
Signals suit code you do not own; your own code can call what it needs.
A system check returns messages with a level, a hint, and a stable id; errors stop commands.
Rules about production settings are deploy checks, run with check --deploy.
Key terms
Use Table 40.5 to explain this chapter’s ideas in your own words.
Table 40.5 — Key terms from Chapter 40
Term
Meaning
App registry
Django's record of every installed app and its models, built at startup.
AppConfig.ready()
The method Django calls on each app once every app is loaded.
Signal
A named event sent to every connected receiver.
Receiver
A function connected to a signal.
post_save
The signal Django sends after a model instance is saved.
raw
True when loaddata saves a row exactly as the fixture holds it.
dispatch_uid
A name that keeps a receiver from being connected twice.
System check
A startup check that returns messages with a level, hint, and id.
Deploy check
A system check that runs only with check --deploy.
SILENCED_SYSTEM_CHECKS
The setting that turns off checks by id.
Readiness checkpoint: you are ready for Chapter 41 when uv run python check.py ends with “all checks passed” and 448 tests, uv run python manage.py check --deploy --tag otahque names W002 and W003 on your laptop, accounts/signals.py does not exist, and git log --oneline -1 shows this chapter’s commit.
Git Commit
Your Chapter 40 work was committed once, in Step 10, as “Warn about unsafe settings at startup”: the checks and their registration, the from-address setting, the profile tests, the checks’ tests, the profile card and its styles, and the design note. If you kept the Mini-Challenge, commit it on its own:
Terminal
git add config/tests/test_london.py
git commit -m "Refuse London as the default zone"
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 receiver that runs twice and to where configuration rules belong. They are extension questions, not a gate to the next chapter. Proof files are run with uv run python manage.py shell -v 0 -c "exec(open('NAME').read())" and deleted afterwards.
L1 (Junior): What is a signal?
What the interviewer is testing: Do you know what a signal does, and what it costs?
Flip to check your answerFold answer back
Perfect answer: A signal is a named event. Code sends it, with arguments, and Django calls every receiver connected to it. Django sends post_save after any instance is saved, with the model, the instance, created, and raw; allauth sends user_signed_up after a member signs up. The sender does not know who listens, which is why signals suit reacting to code you do not own. The same property is the cost: reading the code that saves a user does not tell you what else happens. Otahque connects no receiver of its own today.
Code proof: Otahque has no post_save receiver for User:
Output
receivers of post_save for User: False
Common mistakes:
Using a signal to call code in the same app.
Forgetting that bulk_create() and update() send no post_save.
Follow-up the interviewer might ask:
Is a receiver run in a separate thread? (No: in the same thread and transaction, before save() returns.)
How do you test a receiver? (Save, then check its effect; or connect a test receiver and count calls.)
L2 (Mid-Level): Predict what a profile receiver does during loaddata
What the interviewer is testing: Can you follow a signal through fixture loading?
Flip to check your answerFold answer back
Perfect answer:loaddata saves the user row with raw=True and created=True. A receiver that ignores raw creates a profile for that user straight away. Then loaddata reaches the fixture’s own profile row for the same user, and the database refuses it: one profile per user, IntegrityError, and the whole fixture is rolled back. The guard if created and not raw fixes loading, but not the deeper problem, which Step 4 showed: every other place that creates a profile collides too.
Code proof: the suite with the receiver connected, from Step 4:
Output
Found 440 test(s).
Creating test database for alias 'default'...
ERROR: setUpClass
django.db.utils.IntegrityError: duplicate key value violates
unique constraint "accounts_profile_user_id_key"
ERROR: setUpClass
django.db.utils.IntegrityError: duplicate key value violates
unique constraint "accounts_profile_user_id_key"
ERROR: setUpClass
django.db.utils.IntegrityError: duplicate key value violates
unique constraint "accounts_profile_user_id_key"
ERROR: test_a_missing_phone_is_named
django.db.utils.IntegrityError: duplicate key value violates
unique constraint "accounts_profile_user_id_key"
... (5 more like these)
Ran 431 tests in ...s
FAILED (failures=3, errors=6)
Common mistakes:
Disconnecting the receiver around loaddata in a test, and hiding the bug from production imports.
Assuming loaddata calls save() on the model; it saves raw rows.
Follow-up the interviewer might ask:
Does raw exist for pre_save too? (Yes.)
What else saves rows without your save()? (bulk_create() and update(), which send no post_save at all.)
L3 (Senior): Defend making the profile on first use
What the interviewer is testing: Can you defend a design against a popular tutorial?
Flip to check your answerFold answer back
Perfect answer: Most members never need a profile at sign-up; it matters when they set a time zone or an event asks for a fact. Profile.of() is a get_or_create() on a unique column, so whoever asks first creates it and everyone else reads it: at most one, made on first use. Every caller is visible by searching for one name, it never runs during loaddata, and code that creates a profile on purpose still works. A signal would make every user save do more than it says, and Step 4 showed what that breaks. I would revisit if nearly every page needed a profile, where an eager row would save a query per page.
Figure 40.6 — Why profiles are made on first use.
Behind the scenes:
Profile.of(user), twice
get_or_create(user=user) -> created
get_or_create(user=user) -> found
the unique rule is the backstop
Code proof: the profile tests:
Output
Found 4 test(s).
Creating test database for alias 'default'...
...
Ran 4 tests in ...s
OK
Common mistakes:
Reading user.profile directly, which raises when no profile exists yet.
Relying on get_or_create() without a unique rule under it.
Follow-up the interviewer might ask:
What if two requests call Profile.of() at the same moment? (The unique rule refuses the second insert, and get_or_create() reads the row the first made.)
Where does Otahque read facts without making a profile? (fact_of(), which returns an empty value if there is none.)
L4 (Staff): Every member gets two welcome emails. Diagnose it
What the interviewer is testing: Can you find a receiver connected twice?
Flip to check your answerFold answer back
Perfect answer: The receiver runs twice, so it is connected twice. Django keeps one connection per function object, or per dispatch_uid, so calling connect() twice with the same function is harmless. Two function objects are not: the module is imported under two names, such as signals in one place and accounts.signals in another, or the receiver is defined inside ready() or another function that runs twice. I would search for the module’s imports, move the import to one place, ready(), give the receiver a dispatch_uid, and add a test that counts the emails a sign-up sends.
Figure 40.7 — A receiver that runs twice.
Behind the scenes:
Django's key for a receiver
(id(function), id(sender)) or dispatch_uid
same function twice -> one key
two function objects -> two keys
Code proof: one function connected twice, and two function objects:
Output
same function twice: 1
two function objects: 2
Common mistakes:
Adding a “sent already” flag instead of finding the second connection.
Using weak=False without understanding that it keeps a closure alive.
Follow-up the interviewer might ask:
How would the test count emails? (len(mail.outbox) after posting the sign-up form.)
Why does ready() sometimes run twice in tests? (Tests that change INSTALLED_APPS rebuild the app registry, and Django’s documentation warns that ready() may then run more than once.)
L5 (Lead): Defend system checks over runtime assertions
What the interviewer is testing: Can you choose when and how a configuration rule is enforced?
Flip to check your answerFold answer back
Perfect answer: A wrong setting found by an assert in a view fails on the first request that reaches it, in production, as a 500. An assert in settings.py fails at startup but with a bare traceback, cannot be silenced deliberately, and runs in tests too. A system check runs before the server accepts a request, prints a message with a hint and a stable id, can be silenced by id when a team decides it does not apply, and, as a deploy check, runs exactly when production settings are judged. Otahque’s rule: facts that must hold everywhere are ordinary checks (E001); facts about production are deploy checks (W002, W003), run by the release (Chapter 63).
Figure 40.8 — Where a configuration rule is enforced.
Behind the scenes:
One rule, three places
assert in a view first request, 500
assert in settings startup, traceback
system check startup, id and hint
Code proof: the deploy checks on a laptop’s settings:
Output
System check identified some issues:
WARNINGS:
?: (otahque.W002) The admin is at /admin/, the first address
an attacker tries.
HINT: Set DJANGO_ADMIN_URL to a path that is hard to
guess (Chapter 23).
?: (otahque.W003) Emails would be sent from
webmaster@localhost, which nobody reads.
HINT: Set DJANGO_FROM_EMAIL to an address members can
reply to.
System check identified 2 issues (0 silenced).
Common mistakes:
Writing production rules as ordinary checks, which stop tests.
Silencing a check in settings for every environment to quiet one laptop.
Follow-up the interviewer might ask:
Should a check query the database? (Only if registered with the database tag, which check runs only when asked.)
How would CI fail on warnings too? (check --deploy --fail-level WARNING.)