ContentsClose contents
Pre-release
Chapter 17 · Choosing and creating our user modelCHAPTER 17

Complete six-part pre-release for review. The user model is a proposal; no migration or table is created, and no user is saved until Chapter 18.

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

CHAPTER SEVENTEEN

Choosing and creating our user model

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

Prerequisites: Chapters 2, 5, 7, 8, 15, and 16, including the Chapter 16 project, its 20 passing tests, its empty db.sqlite3, and the practice helper ../practice/setup_django.py

What you’ll build: an accounts app holding Otahque’s proposed user model, which signs in with an email address, together with its manager, five tests that need no database, and a decision record that explains the choice.

Why This Matters

Sai wants to know whether her place at the November meetup is confirmed. Before Otahque can tell her, it has to know that the person asking is Sai, and that the registration it is about to show belongs to her. Chapter 2 wrote this down as a rule: members see their own registration information, and organizers manage only the events assigned to them. Chapter 15’s ERD gave the member a row of their own, with a unique email address and a display name, and no username. Sai signs in with the address she already uses. When Raj decides that “Raj K.” reads better than his full name on an attendee list, he changes his display name, and his sign-in stays the same.

Behind every one of those journeys sits one record: the account that says who someone is. In Django, that record is the user model, and almost everything that follows refers to it. Registrations in Chapter 20 point at a user. Signing in, in Chapter 27, checks a user’s password. Organizer assignments, permissions, and Django’s own admin site all lead back to the same table. That makes the user model a decision that is cheap now and expensive later. Django can create its built-in user table the first time migrate runs, and once that table exists and other tables point at it, switching to a different model cannot be done automatically. Otahque has no tables yet, which is exactly why Chapters 15 and 16 left the database empty: the choice is made here, while it costs nothing to change.

This chapter makes that choice and records why. Otahque’s user signs in with an email address instead of a username, and Django’s default user does not fit that well. You will compare the three ways Django offers to define a user, choose one for stated reasons, and build it test-first. You will also see what Django does with a password, which is not what most people expect, and write the decision down as Otahque’s second decision record.

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

  • explain what Django’s user model is for, and why it is chosen before the first migration;
  • compare Django’s default user, AbstractUser, and AbstractBaseUser with PermissionsMixin, and say what each costs;
  • define a user model that signs in with an email address, with a manager that creates users and superusers;
  • explain how Django stores and checks a password;
  • refer to the user model correctly from other code;
  • record the choice and its consequences in a decision record.

This chapter writes one model, one manager, five tests, and two decision records, and nothing else. It creates no migration and no table, so no user can be saved yet: Chapter 18 creates the tables and adds the tests that save users. There is no sign-up page or sign-in page yet; those arrive in Chapters 27 to 29, and Chapter 27 decides whether members need a profile. Django’s admin site is set up in Chapter 23. Who counts as an organizer or as Otahque’s administrator is a product rule, not a field on the user, and it stays with the chapters on assignments and permissions (20, 23, and 30). Whether two email addresses that differ only in capital letters belong to the same person is an open question, decided in Chapter 21 before anyone can sign up.

PAGE 001

What You Need to Know

Who someone is, and what they may do

Two questions run through every page that is not public. The first is “who is this?”, and the second is “may they do this?”. Keeping them apart avoids a common confusion.

New Concept: authentication, authorization, and the user model

What problem exists? A web application has to recognize returning people and decide what each of them may see and change. Without a shared record of who someone is, every page would invent its own idea of a person.

What did people do before? Each application wrote its own accounts table, its own password checks, and its own rules for who may do what, and each one repeated the same mistakes.

What is a user model? Authentication establishes who someone is, usually from something they know, such as a password. Authorization decides what an authenticated person may do. Django’s authentication system keeps both around one model, the user model: each row is one account, and Django’s sign-in, sessions, permissions, and admin site all work with it.

Why use Django’s? Its password storage, sign-in checks, and permissions are tested by many projects, and other Django components, such as the admin, already know how to use them.

Now let’s use it. The rest of this part decides which user model Otahque has and how other code finds it.

Chapter 2 named four kinds of people, and the user model covers only some of them. A visitor is anyone reading public pages, without an account; a visitor has no row at all. A member has an account and signs in; in the ERD, the MEMBER entity is that account, and in Django it becomes a user. An organizer is a member who has been assigned to manage a particular event. That is a fact about the member and the event together, which the ERD records as an organizer assignment, not as part of the member’s own row. The administrator is the person Chapter 2 makes responsible for accounts and access, including granting and removing organizer access. How that responsibility is given to someone is still an open policy. Django’s own flags, which you meet below, do not settle it.

Choosing the user model before the first migration

Django finds the user model through one setting, AUTH_USER_MODEL. When a project does not set it, its value is 'auth.User': the User model that ships in django.contrib.auth, which Chapter 16’s L5 code proof printed.

New Concept: AUTH_USER_MODEL

What problem exists? Many parts of Django, and later parts of Otahque, need to point at “the user” without knowing in advance which model a project uses.

What did people do before? Code imported Django’s built-in User class directly, and a project that needed different fields had to keep a second “profile” table beside it or change Django itself.

What is AUTH_USER_MODEL? A setting holding a model label, the app label and the model name joined by a dot, such as 'accounts.User'. Django uses the model it names everywhere a user is needed, and the built-in auth.User steps aside. Django calls this a swappable model.

Why set it now? The first migrate creates the user model’s table, and other tables refer to it. Django’s documentation says that changing the setting once those tables exist cannot be done automatically: keys and rows would have to be moved by hand. Setting it before the first migration avoids that work entirely.

Now let’s use it. Otahque sets it to a model of its own, accounts.User.

Django does not require every project to replace the default. Since Django 5.1, its documentation says that a new project “can” set up a custom user model from the start, and asks the reader to consider whether it is right for the project; earlier versions recommended it more strongly, and many tutorials still repeat that older advice. The current position is a choice, so a project needs a reason. Otahque has one. The ERD’s member signs in with a unique email address and has a display name, and no username. Django’s default user has a required, unique username, an email that does not have to be unique, and first_name and last_name fields that the ERD does not ask for. Making the default user sign in by email would need extra code to cope with two accounts sharing an address. A custom model can make the email itself the unique sign-in field.

Three ways to get a user model

Django offers three starting points. Table 17.1 compares what each brings.

Table 17.1 — Three ways to get a user model
Aspect Default auth.User AbstractUser AbstractBaseUser + PermissionsMixin
Sign-in field username, unique username, unless replaced Any unique field you declare
Email Optional, not unique Optional, unless redeclared Declared by you
Name fields first_name, last_name first_name, last_name Only those you declare
Password, last_login Included Included Included
is_active, is_staff, date_joined Included Included Declared by you
Permissions and groups Included Included From PermissionsMixin
Manager Included Needed if username goes Always needed
Code you write None A short class A longer class, every field visible

AbstractUser and AbstractBaseUser are abstract models: classes that hold fields and methods for other models to inherit, and that have no table of their own. AbstractUser is the default user without its table. You inherit everything, then change what you need, such as removing username and making email unique. AbstractBaseUser holds only the core of an account: the hashed password, the time of the last sign-in, and the methods that set and check a password. PermissionsMixin adds is_superuser, membership of groups, and individual permissions, which Chapter 30 uses. Together they give you an account in which every other field is one you declared.

Otahque uses AbstractBaseUser with PermissionsMixin. The reason is clarity, not security. Every field the user table will hold is either declared in Otahque’s own code or comes from one of two small, documented classes, so a reader can see the whole account in one place, and the table holds no name fields that the ERD did not ask for. The cost is real: more lines now, no get_full_name() or email_user() methods, and more configuration when Chapter 23 sets up the admin site.

Prefer AbstractUser?

AbstractUser is a sound choice, and many projects make it. With username = None, a unique email, a display_name, and a manager, it would meet Otahque’s needs in fewer lines, and it keeps Django’s name methods and email helper. Its table also has first_name and last_name columns, left as empty text. Choose it when you want the default behaviour with small changes; choose AbstractBaseUser when you want each field to be a deliberate decision. Both need a custom manager once username is gone, and both need a custom admin and custom forms later. Otahque’s decision record names AbstractUser as the option not chosen, with its reasons.

Telling Django how the model is used

A custom user model answers three questions with class attributes, and supplies a manager.

  • USERNAME_FIELD names the field people sign in with. It must be unique: Django’s sign-in looks up exactly one account by it. Otahque uses 'email'.
  • REQUIRED_FIELDS lists the extra fields that Django’s createsuperuser command asks for, beyond the sign-in field and the password. It must not include USERNAME_FIELD. Otahque lists 'display_name'. It affects only that command; the model’s own field options decide what is required everywhere else.
  • EMAIL_FIELD names the field that holds the email address, which Django’s password reset uses in Chapter 29. For Otahque it is the same field, 'email'.

New Concept: a model manager

What problem exists? Creating a user is more than saving a row. The email has to be tidied, the password has to be hashed, and a superuser needs particular flags. Doing this by hand in every place that creates users would sooner or later miss a step.

What did people do before? They wrote helper functions in different modules and hoped that everyone called the right one.

What is a manager? The object on a model’s class through which Django creates and finds rows, objects by default, as in User.objects. A custom manager adds methods to it. For users, Django expects two: create_user() and create_superuser().

Why write one? Django’s own tools call these methods. createsuperuser calls create_superuser() with the answers it collects. The manager Django provides for its default user expects a username, so a model without one needs its own.

Now let’s use it. Otahque’s UserManager follows a short contract, below.

Django supplies a base class, BaseUserManager, with a normalize_email() method. Otahque’s manager builds on it with two methods:

  • create_user(email, password=None, **extra_fields) refuses an empty email with a ValueError, before anything else happens. It then normalizes the email, builds the user with any other fields, such as display_name, hashes the password, saves the user, and returns it. A password of None stores an unusable password: the account exists, but no password signs in to it.
  • create_superuser(email, password=None, **extra_fields) sets is_staff and is_superuser to True unless they were given. It refuses a superuser with either flag set to anything other than True, then hands over to create_user(), so the email and password rules live in one method.

normalize_email() does less than its name suggests. It lowercases only the part after the @, the domain, so Sai@EXAMPLE.org becomes Sai@example.org. The part before the @ is left as typed, because mail systems may treat its capital letters as significant. Whether Otahque treats Sai@example.org and sai@example.org as one account is the product question that Chapter 21 settles before sign-up. Until then, the model makes no promise either way.

Try it yourself

Que. 1 Chapter 15’s MEMBER entity has id, email, and display_name. Using Table 17.1, say where each comes from in Otahque’s model, and name two fields the table will hold that the ERD did not list.

Flip to check your answerFold answer back

Answer. Django adds id, a BigAutoField, because no field declares a primary key, as with Event. email and display_name are declared in Otahque’s class. Fields the ERD did not list include password and last_login from AbstractBaseUser, is_superuser from PermissionsMixin, and the declared is_active, is_staff, and date_joined. They serve Django’s authentication; they are implementation details, not new product requirements.

How Django stores a password

Under the Hood: what set_password() stores

A user’s password field never holds the password. set_password() passes it to a hasher, which runs a one-way function many times over the password and a salt, a random value chosen for this password alone. Django 6.1’s default hasher is PBKDF2 with SHA-256, and the installed Django 6.1.2 repeats it 1,500,000 times, which makes each guess slow for anyone who steals the table. The field stores four parts joined by dollar signs: the algorithm, the number of iterations, the salt, and the resulting hash. To check a password, check_password() reads the algorithm, iterations, and salt from the stored value, repeats the calculation on what was typed, and compares the two results. Nothing is ever decrypted, because no step can be reversed. Because each password has its own salt, two members with the same password store different values. And because the algorithm and the iteration count are stored with each hash, a later Django can raise the count, or change the algorithm, and upgrade each password when its owner next signs in.

This read-only example shows the parts. You will run something like it in Step 5:

user.set_password('correct horse')
print(user.password.split('$')[:2])
['pbkdf2_sha256', '1500000']

Only the first two parts are printed; the salt and the hash follow. Storing a hash protects members’ passwords if the database is ever copied, but it is not a whole security policy. Which passwords Otahque accepts is set by the password validators already listed in the settings, which Chapter 29 reviews with password reset; the security review in Chapters 59 and 60 revisits both.

Referring to the user from other code

Code outside the accounts app should not import the user class by name. If it wrote from accounts.models import User everywhere, a reusable app, or Django’s own apps, could not work with a project that uses a different model. Django gives two documented ways instead:

  • In a relationship, such as a registration’s link to its member, use the setting itself: models.ForeignKey(settings.AUTH_USER_MODEL, ...). Chapter 20 writes these relationships.
  • In other code, such as a view or a test, call get_user_model() from django.contrib.auth, which returns whichever model the setting names.
On the left, in a zone labelled Chapter 15 ERD, the green MEMBER entity with id as the primary key, email as a unique key, and display_name, above an orange note saying it is a proposed design with a unique email, a display name, and no username. A blue arrow labelled implemented by points to an orange table headed accounts.User, in a zone labelled what we write, listing email as the unique sign-in, display_name as required, password as a hash only, is_active and is_staff, last_login and date_joined, and is_superuser with permissions. Below the table, an orange card for config/settings.py holds AUTH_USER_MODEL equals ’accounts.User’, with an arrow labelled names pointing up to the table. On the right, in a dashed zone labelled later apps, Chapter 20, two dashed grey cards, Registration and Organizer assignment, each linking to a member, join one grey arrow that points to the settings card, and a purple note says each refers to the setting, not the class.
Figure 17.1 — The ERD’s member, Otahque’s user model, and how other code reaches it.

Figure 17.1 puts the pieces together. The ERD stays a design. accounts.User implements its member, the setting names that model, and later code goes through the setting.

In practice: an organizer is not a staff flag

Situation. Sam needs to manage the November meetup, and a teammate suggests ticking is_staff on his account so that he “has access”.

Application. is_staff decides only whether an account may sign in to Django’s admin site, and is_superuser grants every Django permission without assigning any. Neither says which events Sam may manage. In Otahque, that is an organizer assignment for one event, which can be revoked and leaves a record (Chapters 20 and 30). Who may grant it is the administrator’s workflow from Chapter 2, which Chapters 23 and 30 decide.

Consideration. Ticking a framework flag to stand in for a product role works on the first day and leaks access later: Sam could sign in to the admin site, and the next shortcut, is_superuser, would let him change every event. Keep each flag to its documented meaning, and give product roles their own records.

PAGE 002

How We Build It

Start from Chapter 16, in the folder containing manage.py, with your own .env, the locked environment, 20 passing tests, the Event model committed, and a db.sqlite3 with no tables. You create a new app, accounts, with three files of your own: accounts/tests.py, written first; accounts/managers.py; and accounts/models.py. You change one existing file, config/settings.py, twice: once to install the app and once to name the user model. You add two decision records under docs/adr/. A practice script goes in ../practice, beside setup_django.py from Chapter 16. Pages, templates, and the Event model stay as they are. At the end, 25 tests pass, Django loads accounts.User as the user model, no migration file exists, and the database still has no tables.

The Custom Way

This illustration stores accounts by hand, with Python’s sqlite3 and hashlib modules; do not add it to the project:

import hashlib
import sqlite3

db = sqlite3.connect(':memory:')
db.execute(
    'CREATE TABLE users (id INTEGER PRIMARY KEY,'
    ' email TEXT UNIQUE NOT NULL, password TEXT NOT NULL)'
)


def add_user(email, password):
    digest = hashlib.sha256(password.encode()).hexdigest()
    db.execute('INSERT INTO users (email, password)'
               ' VALUES (?, ?)', (email, digest))


add_user('sai@example.org', 'correct horse')
add_user('raj@example.org', 'correct horse')
rows = db.execute('SELECT password FROM users').fetchall()
print(rows[0] == rows[1])
True

It looks careful: the email is unique and the password is hashed. The output shows the first problem. Two members who chose the same password store the same value, so cracking one cracks both, and a table of precomputed hashes cracks common passwords at once. SHA-256 is also fast by design, so an attacker with a stolen table can try a great many guesses quickly. Fixing that means a salt for each password, a deliberately slow function, and a way to upgrade old hashes when the function changes. After that come sign-in and sign-out, sessions, permissions, an admin screen, and password reset, each with its own mistakes to avoid. Django’s user model supplies all of these, and the work below is to describe Otahque’s account so that Django can use them.

The Django Way

Six steps build the model. The tests come before the model, so you see them fail first.

Step 1: Check the starting point

Run every test in the project, beside manage.py, in PowerShell, a macOS shell, or Linux/WSL Bash. With no app named, test runs the tests of every app:

uv run python manage.py test

Expected result, shortened with ... where lines are left out:

Found 20 test(s).
System check identified no issues (0 silenced).
....................
...
Ran 20 tests in ...

OK

Then confirm that the database has no tables, with the query from Chapters 15 and 16. In PowerShell, beside manage.py:

uv run python -m sqlite3 db.sqlite3 `
    "SELECT name FROM sqlite_schema"

In a macOS shell or Linux/WSL Bash, beside manage.py:

uv run python -m sqlite3 db.sqlite3 \
    "SELECT name FROM sqlite_schema"

Expected result: nothing at all. Finally, run git status --short; it should print nothing, because Chapter 16’s work is committed.

Chapters 15 and 16 asked you to rename db.sqlite3 if it already had tables, and to keep the renamed copy until this chapter. If you have such a file, such as db-before-ch15.sqlite3, keep it where it is. A list of its tables cannot tell you whether it holds anything you need, or where it came from, so this chapter makes no decision about it and does not open it. Keeping it costs nothing, and Git does not see it. If the query above does list tables, migrate has run since then: rename the file in the same way, keep the copy, and let Django create a new, empty db.sqlite3 the next time it needs one.

Step 2: Create the accounts app

Chapter 7 proposed an accounts app for everything about who someone is, so that identity does not mix with events. Create it, beside manage.py, in any of the three shells:

uv run python manage.py startapp accounts

The command prints nothing. It creates an accounts folder holding __init__.py, admin.py, apps.py, models.py, tests.py, views.py, and a migrations folder that holds only __init__.py. apps.py defines AccountsConfig, the app’s configuration class, just as Chapter 7’s events app has EventsConfig. Give the generated apps.py its two docstrings, as Chapter 7 did for events/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'

Common Error: an app that already exists

If accounts already exists, from an earlier attempt, startapp stops with CommandError: 'accounts' conflicts with the name of an existing Python module and cannot be used as an app name. Nothing is overwritten. Keep the folder you have and compare its files with the listings in this chapter, rather than deleting it.

Open config/settings.py and add the app to INSTALLED_APPS, after Django’s own apps and before events, so that the code which says who someone is loads before the apps that use it:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'accounts.apps.AccountsConfig',
    'events.apps.EventsConfig',
]

Run the system check:

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

If the class name is mistyped, for example as AccountConfig, the check stops with an ImportError that says Module 'accounts.apps' does not contain a 'AccountConfig' class. Choices are: 'AccountsConfig'. Copy the name it suggests.

Step 3: Write the tests first

The tests describe the user model before it exists. startapp wrote accounts/tests.py with an import and a comment; replace its contents with this listing:

"""Tests for the accounts app."""
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.test import SimpleTestCase

from .models import User


class UserModelTests(SimpleTestCase):
    """The custom user: email, password hash, required fields."""

    def test_user_model_is_accounts_user(self):
        self.assertIs(get_user_model(), User)
        self.assertEqual(User.USERNAME_FIELD, 'email')

    def test_password_is_stored_as_a_hash(self):
        user = User(email='sai@example.org',
                    display_name='Sai')
        user.set_password('correct horse')
        self.assertNotEqual(user.password, 'correct horse')
        self.assertTrue(
            user.password.startswith('pbkdf2_sha256$')
        )
        self.assertTrue(user.check_password('correct horse'))
        self.assertFalse(user.check_password('wrong horse'))

    def test_email_and_display_name_are_required(self):
        user = User()
        user.set_password('correct horse')
        with self.assertRaises(ValidationError) as caught:
            user.full_clean(validate_unique=False)
        self.assertEqual(
            sorted(caught.exception.message_dict),
            ['display_name', 'email'],
        )


class UserManagerTests(SimpleTestCase):
    """The manager's rules for members and superusers."""

    def test_create_user_requires_an_email(self):
        with self.assertRaisesMessage(
            ValueError, 'An email address is required.'
        ):
            User.objects.create_user(
                email='', password='correct horse',
                display_name='Sai',
            )

    def test_superuser_flags_must_be_true(self):
        with self.assertRaisesMessage(
            ValueError, 'needs is_superuser=True.'
        ):
            User.objects.create_superuser(
                email='sam@example.org',
                password='correct horse',
                display_name='Sam',
                is_superuser=False,
            )

Each test checks one promise. The first checks that get_user_model() returns Otahque’s class, which proves the setting is in place, and that people sign in with the email. The second checks that a password becomes a PBKDF2 hash, that the right password is accepted, and that a wrong one is refused. The third builds an empty user with a password and runs full_clean(); exactly two fields must complain, display_name and email, which proves they are required and that nothing else is. validate_unique=False skips the uniqueness check, because checking that no other account has the same email is a database query. The last two tests check the manager’s two refusals by their messages, so that a different error cannot pass by accident; assertRaisesMessage() accepts a message that contains the given text.

All five run without a database, as Chapter 16’s model tests did, and each refusal happens before the manager would save. That also marks their limit. They do not prove that create_user() or create_superuser() stores a user, because there is no table to store one in. Chapter 18 adds those tests once the tables exist.

Run the new tests on their own by naming the app:

uv run python manage.py test accounts

Expected result, shortened with ...:

Found 1 test(s).
System check identified no issues (0 silenced).
E
...
ImportError: Failed to import test module: accounts.tests
...
    from .models import User
ImportError: cannot import name 'User' from ...
...
FAILED (errors=1)

This is the red stage you saw in Chapter 16. accounts/models.py has no User yet, so the test file cannot be imported, and Django reports the whole file as one failed “test”.

Step 4: Write the manager, the model, and the setting

Create accounts/managers.py with the contract from What You Need to Know:

"""How Otahque creates members and superusers."""
from django.contrib.auth.base_user import BaseUserManager


class UserManager(BaseUserManager):
    """Create Otahque users, who sign in with an email."""

    use_in_migrations = True

    def create_user(self, email, password=None,
                    **extra_fields):
        """Create and save a member with this email."""
        if not email:
            raise ValueError('An email address is required.')
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, password=None,
                         **extra_fields):
        """Create and save a member with every permission."""
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        for flag in ('is_staff', 'is_superuser'):
            if extra_fields[flag] is not True:
                raise ValueError(
                    f'A superuser needs {flag}=True.'
                )
        return self.create_user(
            email, password, **extra_fields
        )

self.model is the model this manager is attached to, so the manager never names User itself. save(using=self._db) saves to whichever database the manager was asked to use, which matters only once a project has more than one. use_in_migrations = True makes the manager available inside migrations, as Django’s own user manager does; Chapter 18’s first migration records it. create_superuser() uses setdefault(), which sets a value only when the caller has not given one, so a caller who passes is_superuser=False is refused rather than silently corrected. The manager does not check display_name: the model requires it, so full_clean() and, later, forms report a missing one.

Then replace the contents of accounts/models.py with the model:

"""Otahque's member accounts."""
from django.contrib.auth.models import (
    AbstractBaseUser,
    PermissionsMixin,
)
from django.db import models
from django.utils import timezone

from .managers import UserManager


class User(AbstractBaseUser, PermissionsMixin):
    """An Otahque member, who signs in with an email."""

    email = models.EmailField('email address', unique=True)
    display_name = models.CharField(max_length=100)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    date_joined = models.DateTimeField(default=timezone.now)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    EMAIL_FIELD = 'email'
    REQUIRED_FIELDS = ['display_name']

    def __str__(self):
        return self.email

Table 17.2 explains each field the table will hold.

Table 17.2 — The fields of accounts.User
Field Comes from Purpose
id Added by Django BigAutoField primary key, as for Event
email Declared; unique The sign-in field; at most 254 characters, Django's default
display_name Declared; required The name shown to others, at most 100 characters
password AbstractBaseUser A hash of the password, never the password
last_login AbstractBaseUser When the user last signed in (Chapter 27)
is_active Declared; default True An inactive account cannot sign in
is_staff Declared; default False May sign in to Django's admin site; not an Otahque role
is_superuser, groups, user_permissions PermissionsMixin Django permissions (Chapter 30)
date_joined Declared; default now When the account was created

EmailField is a CharField that also checks that its value looks like an email address. default=timezone.now passes the function itself, without brackets, so that Django calls it for each new user rather than once when the file loads. __str__() returns the email, which is unique, so lists in the admin and error messages name each account unambiguously. Public pages must never show it: other members see the display name, which later templates use. The values 100 for display_name and the default flags are proposals recorded with the model, not product rules from Chapter 2.

Do not run anything yet. The model now exists beside Django’s built-in auth.User, and Django still uses the built-in one, so the two clash.

Common Error: a user model without AUTH_USER_MODEL

If you run check or the tests now, Django stops with four fields.E304 errors, such as Reverse accessor 'Group.user_set' for 'accounts.User.groups' clashes with reverse accessor for 'auth.User.groups'. Each error’s hint suggests adding a related_name, which would silence the clash but leave Django using its own user. The real cause is the missing setting: once AUTH_USER_MODEL names accounts.User, the built-in model steps aside and the clash disappears.

Add the setting to config/settings.py, directly after INSTALLED_APPS:

# Otahque's own user model, set before the first migration.
# See docs/adr/ADR-002-user-model.md.
AUTH_USER_MODEL = 'accounts.User'

The comment says why the line matters and where the reasons are recorded; you write that record in Step 6. Now run every test:

uv run python manage.py test

Expected result, shortened with ...:

Found 25 test(s).
System check identified no issues (0 silenced).
.........................
...
Ran 25 tests in ...

OK

The 20 earlier tests and the 5 new ones pass. Hashing is slow on purpose, so these tests take noticeably longer than Chapter 16’s. Then run the system check, which also applies the rules for user models:

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

The check reports a user model’s most likely mistakes before anything runs. Removing unique=True from email gives (auth.E003) 'User.email' must be unique because it is named as the 'USERNAME_FIELD'. Adding 'email' to REQUIRED_FIELDS gives (auth.E002) The field named as the 'USERNAME_FIELD' for a custom user model must not be included in 'REQUIRED_FIELDS'. A misspelled model name in the setting, such as 'accounts.Users', stops every command with ImproperlyConfigured: AUTH_USER_MODEL refers to model 'accounts.Users' that has not been installed, and so does a correct name when the app is missing from INSTALLED_APPS.

The check cannot see everything. If objects = UserManager() is left out, check still reports no issues, and Django gives the model an ordinary manager without create_user(). The last two tests catch that: they fail with AttributeError: 'Manager' object has no attribute 'create_user', and the same for create_superuser.

Common Error: running migrate to see the table

With the setting in place and no migration for accounts, migrate stops before creating anything, with ValueError: Dependency on app with no migrations: accounts. That is the safety net working: Django’s own apps depend on the user model, which has no migration yet. This message is what Django 6.1.2 was observed to print; the documentation does not promise its wording. A failed migrate leaves db.sqlite3 with no tables, so there is nothing to recover; carry on. If makemigrations has run instead, it has written accounts/migrations/0001_initial.py and events/migrations/0001_initial.py. Keep them: move both into ../practice, so that Chapter 18 starts from no migrations, and do not delete them in this chapter.

Step 5: Inspect the user model

The practice helper from Chapter 16 sets Django up for a script. If you no longer have ../practice/setup_django.py, recreate it from Chapter 16, Step 4. Then create a script that looks at the user model:

import setup_django  # loads Otahque's settings first
from django.conf import settings
from django.contrib.auth import get_user_model

User = get_user_model()
print(settings.AUTH_USER_MODEL, User._meta.db_table)
for field in User._meta.concrete_fields:
    print(field.name, field.get_internal_type())
user = User(email='sai@example.org', display_name='Sai')
user.set_password('correct horse')
print(user.password.split('$')[:2])
print(User.objects.normalize_email('Sai@EXAMPLE.org'))
print(user.is_active, user.is_staff, user.is_superuser)

concrete_fields lists the fields that become columns, leaving out groups and user_permissions, which Chapter 18’s migration stores in tables of their own. Run the script from the folder that holds manage.py, in any of the three shells:

uv run python ../practice/inspect_user.py
accounts.User accounts_user
id BigAutoField
password CharField
last_login DateTimeField
is_superuser BooleanField
email CharField
display_name CharField
is_active BooleanField
is_staff BooleanField
date_joined DateTimeField
['pbkdf2_sha256', '1500000']
Sai@example.org
True False False

The setting names Otahque’s model, whose table will be accounts_user. The fields come in the order Django assembles them: id, the fields inherited from AbstractBaseUser and PermissionsMixin, then Otahque’s own. email reports CharField, because an EmailField is stored as text. The password is a PBKDF2 hash, normalize_email() lowercased only the domain, and a new user is active, not staff, and not a superuser. The user exists only in memory; nothing was saved.

Now ask Django which migrations exist for Otahque’s two apps. In any of the three shells:

uv run python manage.py showmigrations accounts events
accounts
 (no migrations)
events
 (no migrations)

showmigrations lists each app’s migration files and marks the ones applied; it only reads, and creates nothing. Neither app has a migration yet. Run the Step 1 query again: it still prints nothing.

Step 6: Record the decision

Chapter 5 drafted ADR-001 on paper and said that decision records belong in docs/adr/, versioned with the code. Chapter 15 put the ERD in docs/design/. Now the project gets its decision records: ADR-001, transcribed from Chapter 5’s Table 5.4, and ADR-002 for the user model. Both stay Proposed, because nobody responsible for a real Otahque has accepted them. Create a docs/adr folder beside docs/design, with mkdir docs/adr, the same command in every shell. Then create the first file:

# ADR-001: Build a server-rendered Django application

## Status

Proposed, October 2026. Not yet reviewed or accepted.

## Context

Organizers and attendees need one current registration
record. Ownership and capacity rules must hold whatever a
browser sends. Main journeys must work with a keyboard and
on narrow screens. A small volunteer team must be able to
build and maintain the application, and the book's readers
are learning Django.

## Options

- A: a connected form and spreadsheet.
- B: a server-rendered Django application with a database.
- C: a Django API with a separate JavaScript client.

## Decision

Build the first release as one Django application that
renders HTML pages on the server, stores records in a
relational database, and applies Otahque's rules in its
views and models.

## Consequences

One application to build, test, and host. Rules run in one
place. Pages work with links and forms before any
JavaScript. Highly interactive screens need extra work, and
other software has no API until one is added.

## Revisit if

A mobile or partner application needs Otahque's data;
check-in or other work must continue offline; measurement
shows that server rendering cannot meet an agreed
performance target.

## Related

BR-1 to BR-3 and PR-1 to PR-6 (Chapter 2).

The heading shortens Table 5.4’s title so that it fits on one line; the rest follows the table. Then write the new record:

# ADR-002: A custom user model that signs in by email

## Status

Proposed, November 2026. Not yet reviewed or accepted.

## Context

Members sign in with a unique email address and are shown
by a display name; the ERD (docs/design/erd.md) gives a
member no username. Django's default user signs in with a
username and does not require a unique email. The user
model must be chosen before the first migration, because
Django cannot switch it automatically once tables exist.

## Options

- A: Django's default user, with an extra sign-in backend
  that accepts an email address.
- B: AbstractUser, with username removed and email unique.
- C: AbstractBaseUser with PermissionsMixin, declaring each
  remaining field.

## Decision

Option C. accounts.User signs in with a unique email, has
a required display_name, and is created through
UserManager. AUTH_USER_MODEL names it. It implements the
ERD's Member entity.

## Consequences

Every stored field is declared or comes from a small,
documented class. There is more code than option B, no
get_full_name() or email_user(), and the admin site
(Chapter 23) needs a custom user admin. Other code refers
to the model through settings.AUTH_USER_MODEL or
get_user_model(). is_staff and is_superuser are Django
flags, not Otahque's organizer or administrator roles.

## Open questions

Whether addresses that differ only in letter case are one
account is decided in Chapter 21, before sign-up. Until
then, only the domain is lowercased.

## Revisit if

Members need a public username, or sign-in moves to an
outside identity provider. Changing the model after the
first migration needs a planned data migration.

## Related

ADR-001; docs/design/erd.md; PR-4 and PR-6 (Chapter 2).

The ERD should say how its member is built, too. Open docs/design/erd.md and add this section between “Rules that need more than structure” and “Open questions”, with a blank line before and after it:

## Django implementation mapping (proposed)

The Member entity is implemented by the Django model
accounts.User, named by AUTH_USER_MODEL. Django's own
fields (password hash, last sign-in, active and staff
flags, permissions) serve the framework; they add no
product requirement to Member. See
docs/adr/ADR-002-user-model.md.

The ERD stays a design; the section only points from its entity to the model that implements it. The decision record keeps the options not chosen, the costs as well as the benefits, and the question still open, so that someone reading it in a year can tell what was decided and what was not. Check what changed:

git status --short
 M config/settings.py
 M docs/design/erd.md
?? accounts/
?? docs/adr/

?? marks folders Git has not seen before; Git lists a new folder once, not file by file. No migration file appears, and db.sqlite3 does not either, because .gitignore leaves it out.

When something goes wrong

Table 17.3 — User model problems and safe recovery
Symptom Likely cause Safe recovery
CommandError: 'accounts' conflicts with ... startapp ran before Keep the folder; compare its files with the listings
ImportError: ... does not contain a 'AccountConfig' class App class name mistyped in INSTALLED_APPS Use the name the message suggests
ImportError: cannot import name 'User' from 'accounts.models' Step 4 not done yet, or the class name misspelled Write the model, or compare the class line
Four fields.E304 clashes with auth.User AUTH_USER_MODEL not set Add the setting; do not add related_name
(auth.E003) 'User.email' must be unique unique=True left out of email Add it back, as in the listing
(auth.E002) ... must not be included in 'REQUIRED_FIELDS' 'email' listed in REQUIRED_FIELDS List only 'display_name'
ImproperlyConfigured: AUTH_USER_MODEL refers to model ... not installed Model name misspelled, or app missing from INSTALLED_APPS Compare the setting and INSTALLED_APPS with the listings
AttributeError: 'Manager' object has no attribute 'create_user' objects = UserManager() left out Add the line to the model
AssertionError: ['email'] != ['display_name', 'email'] display_name has blank=True or a default Compare the field with the listing
ValueError: Dependency on app with no migrations: accounts migrate was run Nothing to undo; the database has no tables
0001_initial.py files appear makemigrations was run Move them into ../practice; Chapter 18 makes its own
The Step 1 query lists tables migrate ran in an earlier chapter Rename db.sqlite3 and keep the copy as a backup
PAGE 003

Verify Your Work

Work through Table 17.4 from the folder that holds manage.py. The test rows check behaviour, the inspection rows check what Django loaded, and the last rows check that nothing was created that belongs to Chapter 18.

Table 17.4 — Verification checklist for Chapter 17
Check Command or action Expected result
Starting point The Step 1 test run and query Found 20 test(s), OK; no tables
Red stage seen The Step 3 run, before the model ImportError, FAILED (errors=1)
Tests pass uv run python manage.py test Found 25 test(s), OK
Model loads uv run python manage.py check No issues (0 silenced)
User model named uv run python ../practice/inspect_user.py accounts.User accounts_user, then nine fields
Password hashed The same output ['pbkdf2_sha256', '1500000']
No migrations uv run python manage.py showmigrations accounts events (no migrations) for both apps
No tables yet The Step 1 query No output
Decision recorded Open docs/adr/ ADR-001.md and ADR-002-user-model.md, both Proposed
Only expected changes git status --short config/settings.py, docs/design/erd.md, accounts/, docs/adr/
Not verified yet Saving a user, createsuperuser Chapter 18, once tables exist

The last row matters as much as the others. Nothing in this chapter has saved a user, so nothing has yet shown that create_user() stores a normalized email and a usable hash, or that createsuperuser asks for an email and a display name. Chapter 18 tests both against a real table.

PAGE 004

Checkpoint: Quiz and Challenge

Quiz

Que. 2 Why does Otahque choose its user model in this chapter, rather than after the first migrate?

Flip to check your answerFold answer back

Answer. The first migrate creates the user model’s table, and other tables refer to it. Django cannot switch the user model automatically once those tables exist, so changing it later would mean moving keys and rows by hand. With no tables yet, the choice costs nothing to make.

Que. 3 A teammate writes from accounts.models import User in the Registration model in Chapter 20. What should they write instead, and why?

Flip to check your answerFold answer back

Answer. models.ForeignKey(settings.AUTH_USER_MODEL, ...), which refers to whichever model the setting names. Code outside a relationship would call get_user_model(). Both keep working if the user model ever changes, and Django can resolve the model when the apps load.

Que. 4 Two members choose the same password. Are their stored password values the same?

Flip to check your answerFold answer back

Answer. No. set_password() picks a new random salt for each password, and the salt is part of what is hashed, so the stored values differ. check_password() reads each salt back from the stored value to check a typed password.

Que. 5 What does User.objects.normalize_email('Raj@EXAMPLE.ORG') return, and what question does that leave open?

Flip to check your answerFold answer back

Answer. Raj@example.org: only the domain is lowercased. Whether Raj@example.org and raj@example.org count as one account is a product decision for Chapter 21, made before anyone can sign up.

Que. 6 The five tests pass. Have they proved that create_user() saves a user?

Flip to check your answerFold answer back

Answer. No. They prove that the setting names Otahque’s model, that passwords are hashed, that email and display name are required, and that the manager refuses an empty email and a superuser without its flags. Every refusal happens before the save. Saving needs a table, so Chapter 18 tests successful creation.

Mini-Challenge

Que. 7 A teammate proposes adding is_organizer = models.BooleanField(default=False) to accounts.User, so that pages can check user.is_organizer. Using the ERD and Chapter 2’s rules, explain in your notes why Otahque records an organizer assignment instead. Do not change accounts/models.py: the user model is complete for this chapter, and Chapter 18 starts from it as it is.

Flip to check your answerFold answer back

Answer. A flag on the user answers the wrong question. Chapter 2 says organizers manage only the events assigned to them, so the fact to record is “this member organizes this event”, which belongs to a member and an event together; one boolean would let any organizer manage every event. Organizer access is also granted and removed through the administrator’s workflow, and the ERD’s ORGANIZER ASSIGNMENT keeps assigned_at and revoked_at, so removing access leaves a record of who had it and when, while turning a flag off erases that history. A member can organize one event and attend another, which an assignment row expresses directly. A flag would also invite confusion with is_staff, which is only Django’s admin-site gate. Chapter 20 models the assignment and Chapter 30 checks it.

What We Learned

  • Authentication establishes who someone is; authorization decides what they may do. Django’s user model is the account record both rely on.
  • AUTH_USER_MODEL names the user model. It is set before the first migration, because Django cannot switch it automatically once tables refer to it.
  • Django permits a custom user model from the start; Otahque chooses one because its members sign in with a unique email address and have no username.
  • AbstractUser changes the default user; AbstractBaseUser with PermissionsMixin starts from the core of an account, so every other field is declared. Both need a manager once username is gone.
  • USERNAME_FIELD, REQUIRED_FIELDS, and EMAIL_FIELD tell Django how the model is used; the manager’s create_user() and create_superuser() tell it how to create users.
  • A password is stored as a salted, slow, one-way hash with its algorithm and iteration count, and checked by repeating the calculation.
  • Other code refers to the user through settings.AUTH_USER_MODEL in relationships and get_user_model() elsewhere.
  • is_staff and is_superuser are Django flags, not Otahque’s organizer or administrator roles.

Key terms

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

Table 17.5 — Key terms from Chapter 17
Term Meaning
Authentication Establishing who someone is, usually with a password.
Authorization Deciding what an authenticated person may do.
User model The model whose rows are accounts, used by Django's authentication.
AUTH_USER_MODEL The setting naming the user model as 'app_label.ModelName'.
Swappable model A built-in model, such as auth.User, that a setting can replace.
Abstract model A model class that other models inherit from, with no table of its own.
AbstractBaseUser The core of an account: password, last_login, and password methods.
PermissionsMixin Adds is_superuser, groups, and permissions to a user model.
USERNAME_FIELD The unique field people sign in with.
REQUIRED_FIELDS Extra fields that createsuperuser asks for.
Manager The object, usually objects, through which a model creates and finds rows.
Hash The result of a one-way function; it cannot be turned back into the input.
Salt A random value hashed with each password so that equal passwords differ.
get_user_model() Returns the model that AUTH_USER_MODEL names.

Readiness checkpoint: you are ready for Chapter 18 when all 25 tests pass, manage.py check reports no issues, inspect_user.py prints the output shown in Step 5, no migration file exists, the Step 1 query still prints nothing, and the work below is committed. Explain, in a sentence, why migrate now refuses to run, and what Chapter 18 must do first. Return to the relevant step if any result is missing.

Git Commit

Stage the new app, the settings, and the decision records, and check what is staged, in PowerShell, a macOS shell, or Linux/WSL Bash, beside manage.py:

git add accounts config/settings.py docs
git status --short
A  accounts/__init__.py
A  accounts/admin.py
A  accounts/apps.py
A  accounts/managers.py
A  accounts/migrations/__init__.py
A  accounts/models.py
A  accounts/tests.py
A  accounts/views.py
M  config/settings.py
A  docs/adr/ADR-001.md
A  docs/adr/ADR-002-user-model.md
M  docs/design/erd.md

A in the first column marks a new file staged for the commit, and M a staged change. admin.py and views.py are still the files startapp wrote; they are committed now so that the app is complete, and later chapters fill them. No __pycache__ folder appears, because .gitignore leaves it out. Then record the commit:

git commit -m "Add the proposed email sign-in user model"
PAGE 005

Test Your Knowledge: Interview Questions

These five questions rehearse the chapter at interview level, one at each of five levels from junior to lead. L1 and L2 check what you have just learned. L3 asks what happens inside Django when a password is stored. L4 and L5 look ahead to a growing application: attempt them now, and return to them after Chapters 18 and 20. They are extension questions, not a gate to the next chapter. Each code proof is a short file in the practice folder that starts by importing setup_django.py; run it from the folder that holds manage.py with uv run python ../practice/ followed by the file name, in PowerShell, a macOS shell, or Linux/WSL Bash.

L1 (Junior): What is AUTH_USER_MODEL, and why would a project set it?

What the interviewer is testing: Do you know how Django finds the user model, and when the choice has to be made?

Flip to check your answerFold answer back

Perfect answer: AUTH_USER_MODEL is the setting that names the model Django uses for accounts, as an app label and a model name, such as 'accounts.User'. Its default is Django’s own auth.User. A project sets it when the default does not fit, for example when people sign in with an email address instead of a username. Django then uses that model for sign-in, permissions, and the admin, and the built-in user steps aside. The setting must be chosen before the first migrate, because the user table is created then and other tables refer to it; changing it afterwards is not automatic. Code refers to the model through the setting or get_user_model(), never by importing the class.

Table 17.6 — Default and custom user models compared
Question Default (auth.User) Otahque (accounts.User)
AUTH_USER_MODEL 'auth.User', unset 'accounts.User'
People sign in with A username An email address
Email unique No Yes
Table auth_user accounts_user
Must be decided Before the first migrate Before the first migrate

Behind the scenes:

unset        -> 'auth.User' is the user model
set          -> 'accounts.User'; auth.User is swapped out
first migrate -> creates the named model's table
change later -> keys and rows moved by hand

Code proof: the setting, the model Django uses, and the built-in model stepping aside:

import setup_django
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.models import User as DefaultUser

print(settings.AUTH_USER_MODEL)
print(get_user_model()._meta.label)
print(DefaultUser._meta.label, 'swapped for',
      DefaultUser._meta.swapped)
accounts.User
accounts.User
auth.User swapped for accounts.User

_meta.swapped names the model that replaced auth.User. Django creates no table for a swapped model.

Common mistakes:

  • Running migrate before deciding, then trying to change the setting.
  • Writing the setting as a module path, such as 'accounts.models.User', instead of 'app_label.ModelName'.
  • Importing django.contrib.auth.models.User in project code after swapping it out.

Follow-up the interviewer might ask:

  • “When would you keep the default user model?”
  • “Where else in a project would you expect the user model to be referred to?”

L2 (Mid-Level): AbstractUser or AbstractBaseUser with PermissionsMixin: how do you choose?

What the interviewer is testing: Can you weigh code you inherit against code you own, and name the costs of each choice?

Flip to check your answerFold answer back
Five numbered steps. List the fields the product needs. AbstractUser brings a username and name fields. AbstractBaseUser means declaring each field. Both need a manager for email sign-in. Record the trade-off in a decision record.
Figure 17.2 — Choosing a base class for a custom user.

Perfect answer: Start from the account the product needs, then compare what each base class brings. AbstractUser is the complete default user without its table: username, email, first and last names, the staff and active flags, the join date, permissions, and helper methods such as get_full_name(). It suits a project that wants the default with small changes, and it is less code. AbstractBaseUser provides only the password, the last sign-in time, and the password methods; PermissionsMixin adds Django’s permissions. Every other field is yours to declare, so the account holds exactly what you chose, and the code shows it. It costs more lines, and the admin and forms need more configuration because they expect the default fields. Both need a custom manager when username is removed. For Otahque, where members sign in by email and have a display name instead of first and last names, I chose AbstractBaseUser for clarity, and recorded AbstractUser as a sound alternative in the decision record.

Behind the scenes:

AbstractUser     -> default fields and methods, no table
AbstractBaseUser -> password, last_login, password methods
PermissionsMixin -> is_superuser, groups, permissions
either + email   -> USERNAME_FIELD and a custom manager

Code proof: the fields Otahque’s model leaves out, and the one it adds:

import setup_django
from django.contrib.auth.models import AbstractUser
from accounts.models import User

ours = {field.name for field in User._meta.fields}
theirs = {field.name for field in AbstractUser._meta.fields}
print('only AbstractUser:', sorted(theirs - ours))
print('only ours:', sorted(ours - theirs - {'id'}))
print(hasattr(User, 'get_full_name'),
      hasattr(AbstractUser, 'get_full_name'))
only AbstractUser: ['first_name', 'last_name', 'username']
only ours: ['display_name']
False True

id is left out of the comparison because an abstract model has no primary key of its own. The last line shows a method AbstractUser provides and Otahque’s model does not.

Common mistakes:

  • Choosing AbstractBaseUser and forgetting PermissionsMixin, then finding that permissions and the admin do not work.
  • Removing username from AbstractUser without writing a manager.
  • Treating the choice as a security decision rather than one of fit and maintenance.

Follow-up the interviewer might ask:

  • “What would you need to change in the admin for each choice?”
  • “When would a separate profile model be better than more fields on the user?”

L3 (Senior): How does Django store and check a password?

What the interviewer is testing: Do you understand salted, slow hashing, and why nothing is decrypted?

Flip to check your answerFold answer back
Five numbered steps. set_password() receives the password. A new salt is chosen and PBKDF2 runs 1,500,000 times. The field stores the algorithm, iterations, salt, and hash. check_password() repeats the calculation and compares. No plain text is stored and nothing is decrypted.
Figure 17.3 — How a password becomes a stored hash.

Perfect answer: set_password() passes the password to the first hasher in Django’s PASSWORD_HASHERS setting, which by default is PBKDF2 with SHA-256. The hasher chooses a random salt for this password, applies a one-way function many times, 1,500,000 in Django 6.1.2, and returns algorithm$iterations$salt$hash, which is what the password field stores. check_password() reads the algorithm, iteration count, and salt from that value, repeats the calculation on the password typed, and compares the results in constant time. Nothing is decrypted, because the function cannot be reversed. The salt means equal passwords give different values and precomputed tables do not help; the iteration count makes each guess slow. Because the parameters are stored with each hash, a newer Django with a higher count, or a different algorithm, can upgrade a hash when its owner next signs in. set_password(None) stores an unusable password, for accounts that must not sign in with one.

Behind the scenes:

set_password(raw) -> new salt; PBKDF2-SHA256, many times
stored            -> pbkdf2_sha256$1500000$salt$hash
check_password()  -> recompute with stored salt, compare
set_password(None) -> unusable: no password matches

Code proof: the same password hashed twice, then checked:

import setup_django
from django.contrib.auth.hashers import (
    check_password,
    make_password,
)

first = make_password('correct horse')
second = make_password('correct horse')
print(first == second)
print(first.split('$')[:2])
print(check_password('correct horse', first))
print(check_password('correct horse', make_password(None)))
False
['pbkdf2_sha256', '1500000']
True
False

make_password() is the function set_password() uses. Different salts make the two values differ, the right password still checks, and no password matches an unusable one.

Common mistakes:

  • Assigning user.password = 'secret' directly, which stores the plain text and makes every check fail.
  • Hashing passwords with a fast general-purpose hash, such as plain SHA-256.
  • Believing an administrator can look up a member’s password.

Follow-up the interviewer might ask:

  • “How would you raise the cost of hashing for existing users?”
  • “What should a site do if its database of hashes is stolen?”

L4 (Staff): Another app needs to point at the user. How should it refer to it, and why?

What the interviewer is testing: Can you keep apps independent of one concrete user class, and explain how Django resolves the reference?

Flip to check your answerFold answer back
Five numbered steps. In relationships, use settings.AUTH_USER_MODEL. In other code, call get_user_model(). Django resolves the model when the apps load. Migrations depend on the setting, not the class. Apps keep working with whichever user model a project names.
Figure 17.4 — Referring to the user without naming its class.

Perfect answer: In a model relationship, such as a registration’s member, write models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=...). The setting is a string label, so Django can resolve it after all apps are loaded, without import-order problems, and the migration it generates depends on the setting rather than on a particular app. In code that runs after start-up, such as views, forms, and tests, call get_user_model(), which returns the class the setting names. Importing accounts.models.User directly would tie the app to one project’s model, would break if the model changed, and in a reusable app would ignore the project’s choice. Inside the accounts app itself, importing its own model is fine. Chapter 20 uses this rule for Registration and Organizer assignment.

Behind the scenes:

ForeignKey(AUTH_USER_MODEL) -> a label, resolved later
get_user_model()     -> the class, after apps are loaded
migration            -> depends on the swappable setting
import accounts.User -> only inside accounts

Code proof: a practice model that points at the setting, resolved to Otahque’s class:

import setup_django
from django.conf import settings
from django.db import models


class Note(models.Model):
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE
    )

    class Meta:
        app_label = 'events'


print(settings.AUTH_USER_MODEL)
print(Note._meta.get_field('author').related_model)
accounts.User
<class 'accounts.models.User'>

The practice model exists only while the script runs; it is not added to the project. The relationship was written with a string, and Django turned it into the class.

Common mistakes:

  • Copying 'auth.User' into a relationship from an older tutorial, which check refuses with fields.E301 once the model is swapped out.
  • Importing django.contrib.auth.models.User in a project that has replaced it.
  • Writing 'accounts.User' as a literal in many places instead of using the setting.

Follow-up the interviewer might ask:

  • “Why does a relationship use the setting, but a view use get_user_model()?”
  • “What does the generated migration for such a relationship depend on?”

L5 (Lead): After launch, the team wants a different user model. What is involved, and how would you plan it?

What the interviewer is testing: Can you judge the cost of a late schema change and plan it safely, rather than treating it as a settings edit?

Flip to check your answerFold answer back
Five numbered steps. Tables and keys point at the existing user table. Inventory every reference and every row. Create the new model, copy the data, and move the keys. Rehearse on a copy and plan the switch. Avoid it by choosing before the first migrate.
Figure 17.5 — What changing the user model after launch involves.

Perfect answer: Changing AUTH_USER_MODEL after tables exist is not a settings change. Django’s documentation says it cannot be done automatically: the user model must be created in its app’s first migration, every foreign key to the old table must move to the new one, and Django’s own tables for permissions, groups, admin history, and sessions refer to it too. I would first ask whether the need can be met without swapping, for example by adding fields to the current custom model with an ordinary migration, or by adding a profile model. If a swap is unavoidable, I would inventory every reference and row, write the new model and its migrations, copy users and their password hashes, which stay valid, move each foreign key in a data migration, and rehearse the whole change on a copy of production data with a tested way back. I would schedule it with the team, record it as a new decision record that supersedes the old one, and verify sign-in, permissions, and ownership checks afterwards. The cheapest version is the one Otahque took: decide before the first migrate.

Behind the scenes:

user model -> in its app's first migration
tables     -> auth, admin, sessions, our own keys
swap       -> new model, copy rows, move keys
better     -> extend the current model, or add a profile

Code proof: the built-in user is the swappable model, and every migration that depends on the user depends on the first migration of the app the setting names:

import setup_django
from django.conf import settings
from django.contrib.auth.models import User as DefaultUser
from django.db import migrations

print(DefaultUser._meta.swappable)
dependency = migrations.swappable_dependency(
    settings.AUTH_USER_MODEL
)
print(dependency)
AUTH_USER_MODEL
('accounts', '__first__')

__first__ means “the first migration of accounts”, which is why Chapter 18 must create accounts.User in accounts/migrations/0001_initial.py.

Common mistakes:

  • Changing the setting on a live project and running migrate, expecting Django to move the data.
  • Forgetting Django’s own tables that refer to the user.
  • Swapping when an extra field or a profile would have met the need.

Follow-up the interviewer might ask:

  • “How would you keep members signed in, or not, during the switch?”
  • “What would you put in the decision record that supersedes ADR-002?”

Next: Chapter 18 creates Otahque’s first migrations and tables, starting with accounts.User, and tests saving users for the first time.

PAGE 006