The Analogy: A Shipyard Laying the Keel Before the Hull
A shipyard begins every vessel with one act: laying the keel, the single steel backbone that runs stem to stern along the bottom of the hull. Every frame, bulkhead, and deck that follows is measured from the keel and fastened to it. At this first moment the yard can choose the keel freely -- its length, its section, its alloy -- because nothing is attached to it yet and no measurement anywhere depends on it.
That freedom lasts exactly until the first frame goes up. Once frames are riveted to the keel and the hull is plated over, the keel's dimensions are baked into thousands of downstream measurements. A standard keel suits almost every vessel; a specialised one -- a deep ballast keel for a racing yacht, a reinforced keel for an ice-breaker -- is entirely possible, but it has to be declared before the frames are cut, because the frames are cut to match it.
Everyone who fits the ship out afterwards takes the keel and frame plan as settled fact. The engine yard mounts its bedplate to frames whose spacing came from the keel; the pipefitters, electricians, and riggers run their systems against the same published plan and never re-measure the backbone themselves. They build cheaply and quickly precisely because they do not have to question it -- they trust that the keel was decided correctly at the start.
The catastrophe is deciding, after the ship is launched and loaded with cargo, that the keel should have been a different one. Now every frame, plate, pipe, and cable measured from the old backbone has to be cut loose, the cargo offloaded, and the hull dragged back into dry dock for a rebuild that costs more than starting a new ship from bare steel. The keel had to be right before the first frame was raised. Changing it once the vessel is in service is not an adjustment; it is a demolition wearing the word "migration."
Syntax or Core Structure
Django ships a perfectly good user model, but the model your project uses is a keel decision: name it with one settings line before your first migration and it costs nothing, change it afterward and you are back in dry dock. There are two ways to lay your own. AbstractUser keeps every default field and lets you add to it; AbstractBaseUser strips back to password handling and hands you the frame plan to redraw yourself. The stand-in below shows what each starting point leaves you holding.
# settings.py -- the one line that must exist before the first migrate
AUTH_USER_MODEL = "accounts.User"
# accounts/models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
phone = models.CharField(max_length=20, blank=True)
That is the whole recommended path: subclass AbstractUser, add the fields you want, and point AUTH_USER_MODEL at it. AbstractBaseUser is the other option, and it gives you far less for free. The stand-in models both as lists of the fields each starting point leaves in your table, so you can see exactly what "extend" keeps that "rebuild" makes you re-declare.
DEFAULT_FIELDS = ["id", "username", "email", "password", "is_staff", "is_active"]
def abstract_user(extra):
# AbstractUser: inherit every default field, then add your own
return DEFAULT_FIELDS + extra
def abstract_base_user(chosen):
# AbstractBaseUser: start from password handling, re-declare the rest
return ["id", "password"] + chosen
extended = abstract_user(["phone"])
scratch = abstract_base_user(["email", "is_active"])
print("AbstractUser fields: " + ", ".join(extended))
print("AbstractBaseUser fields: " + ", ".join(scratch))
print("extend keeps username: " + str("username" in extended))
print("scratch keeps username: " + str("username" in scratch))
Output:
AbstractUser fields: id, username, email, password, is_staff, is_active, phone
AbstractBaseUser fields: id, password, email, is_active
extend keeps username: True
scratch keeps username: False
Extending inherits the whole default table and simply appends phone; rebuilding starts almost bare and forces you to re-declare everything you still want, including the username field you may not even keep. Both are legitimate keels. The point is that you lay one of them once, at the start, and everything above is measured from it.
Technical Depth: Extend or Rebuild, and the One Deadline That Never Moves
Two base classes, two levels of control
The two starting points differ in how much they hand you and how much they make you draw yourself.
| Starting point | You inherit | You must supply | Reach for it when |
|---|---|---|---|
| AbstractUser | username, email, names, permissions, is_staff and is_active | only the extra fields you add | you want the standard user plus a column or two |
| AbstractBaseUser | password storage and last_login, nothing else | USERNAME_FIELD, REQUIRED_FIELDS, a manager, and PermissionsMixin for permissions | your identity is fundamentally different, such as email-only with no username |
The cost of the swap depends entirely on when
The title of this lesson is not a slogan. The same change -- "use a different user model" -- has three wildly different price tags depending on the phase you attempt it in.
| Moment you switch | What it costs |
|---|---|
| Before the first migration | one settings line and an empty initial migration; free |
| After migrating, before real data | delete the migrations and regenerate them; a chore with no data at risk |
| In production, with data and foreign keys | a hand-written data migration, downtime, and every third-party foreign key to reconcile; avoid |
Reference the model, never the class
A foreign key that names auth.User directly is a frame bolted to the wrong keel: the day AUTH_USER_MODEL changes, that reference still points at a model the project no longer uses. Every relation to the user must name settings.AUTH_USER_MODEL instead, and code that needs the class itself must call get_user_model() rather than importing User. The audit below scans a project's declared foreign-key targets against the configured user model.
AUTH_USER_MODEL = "accounts.User"
MODELS = [
("orders.Order", "auth.User"),
("billing.Invoice", "accounts.User"),
("blog.Comment", "auth.User"),
("profiles.Profile", "accounts.User"),
]
def audit(models, user_model):
broken = []
for name, target in models:
if target != user_model:
broken.append(name)
return broken
bad = audit(MODELS, AUTH_USER_MODEL)
print("user model: " + AUTH_USER_MODEL)
print("models checked: " + str(len(MODELS)))
for name in bad:
print(" dangling FK: " + name)
print("safe: " + str(len(MODELS) - len(bad)) + "/" + str(len(MODELS)))
Output:
user model: accounts.User
models checked: 4
dangling FK: orders.Order
dangling FK: blog.Comment
safe: 2/4
Two of the four relations were bolted straight to auth.User and are now dangling; the two that named accounts.User -- what settings.AUTH_USER_MODEL resolves to -- are safe. Written correctly the first time, all four would read settings.AUTH_USER_MODEL and the audit would find nothing. This is the cheap insurance that keeps the expensive swap from ever becoming necessary.
Real World Example: An Email-First User Laid Down on Day One
Plenty of products never want a username; the login identifier is the email address. That is the textbook reason to lay a custom keel with AbstractBaseUser: set USERNAME_FIELD = "email", drop the username column, and give the model a manager that normalises the address before it is stored, so that two people cannot register the same mailbox in different letter-casing. The program below is that manager reduced to its identity logic. It creates users, refuses blanks and duplicates, and logs someone in by email no matter how they capitalised it. The real manager also runs the password through set_password; that concern belongs to the auth-system lesson and is left out here so the focus stays on identity.
def normalize_email(raw):
return raw.strip().lower()
class UserManager:
def __init__(self):
self.rows = []
self.next_id = 1
def create_user(self, email):
email = normalize_email(email)
if email == "":
return "ERROR email is required"
for u in self.rows:
if u["email"] == email:
return "ERROR email already registered"
row = {"id": self.next_id, "email": email, "is_active": True}
self.rows.append(row)
self.next_id = self.next_id + 1
return "created id=" + str(row["id"]) + " " + email
def find_by_email(mgr, email):
email = normalize_email(email)
for u in mgr.rows:
if u["email"] == email and u["is_active"]:
return u["id"]
return None
mgr = UserManager()
print(mgr.create_user(" Ada@Example.COM "))
print(mgr.create_user("bob@example.com"))
print(mgr.create_user("ada@example.com"))
print(mgr.create_user(" "))
print("users: " + str(len(mgr.rows)))
print("login ADA@example.com -> id " + str(find_by_email(mgr, "ADA@example.com")))
print("login carol@example.com -> " + str(find_by_email(mgr, "carol@example.com")))
Output:
created id=1 ada@example.com
created id=2 bob@example.com
ERROR email already registered
ERROR email is required
users: 2
login ADA@example.com -> id 1
login carol@example.com -> None
Follow the trace. The first address arrives as " Ada@Example.COM " with leading spaces and mixed case, but normalize_email strips and lowercases it to ada@example.com before any row is built, so the stored record and every later comparison share one canonical form. bob registers cleanly as id 2. The third call submits ada@example.com a second time; the loop finds the existing row and rejects it as a duplicate rather than quietly minting a second account. The blank submission collapses to the empty string and is turned away before an id is spent. Two rows survive, and the id counter has advanced exactly twice.
The design gets several things right that are worth naming. Email normalization lives in exactly one function, so creation and lookup can never disagree about what "the same address" means. Because find_by_email normalizes its argument too, a login typed as ADA@example.com locates the row stored as ada@example.com with no second code path and no duplicate normalization rule to drift out of sync. The is_active flag is consulted at login time, so disabling an account is a one-field change instead of a destructive delete. And the manager owns both the id counter and the uniqueness scan, which is precisely the role Django's UserManager plays around a custom user model: the model describes the columns, the manager centralizes how rows are created and found.
That said, this excerpt would be dangerous shipped as-is, and the flaws are instructive. It stores no password at all: a real custom user needs set_password and a hasher, and find_by_email here proves only that an account exists, not that the caller knows its secret, so it is account lookup and not authentication. Uniqueness is enforced by a Python loop rather than a database UNIQUE constraint, so two concurrent create_user calls can both pass the scan and both insert before either commits. The normalization is subtly wrong for real email: it lowercases the entire address, whereas Django's BaseUserManager.normalize_email lowercases only the domain, because the local part before the @ is technically case-sensitive; two genuinely distinct addresses that differ only in local-part case would be merged here. And nothing ties this manager to a swappable model: there is no AUTH_USER_MODEL indirection, so a foreign key written against it directly would reproduce the exact hard-coding the Technical Depth section warned about.
Common Mistakes
- Switching
AUTH_USER_MODELafter the first migration has run. This is the deadline the whole lesson turns on. Oncemigratehas createdauth_userand other tables carry foreign keys to it, changing the setting means Django wants to drop and recreate the user table under live data. Decide before the first migration, every time.
- Referencing
get_user_model()at import time. Called at the top of a module, it runs before the app registry is ready and raises, or worse, captures the wrong model. Call it inside functions and methods, and for foreign keys use the stringsettings.AUTH_USER_MODELso resolution is deferred.
- Pointing a
ForeignKeyatauth.Useror the importedUserclass. Both hard-code the model. The moment the project swaps in a custom user, those relations still point at the abandoned table. Always writemodels.ForeignKey(settings.AUTH_USER_MODEL, ...).
- Reaching for
AbstractBaseUserwhenAbstractUserwould have done.AbstractBaseUsergives you only an id and a password; you then rebuild the username, email, name, staff and permissions machinery by hand. If you just need one or two extra columns, extendAbstractUserand add the fields. Drop toAbstractBaseUseronly when the identity model itself must change.
- Shipping a custom user with no manager. A model that extends
AbstractBaseUserhas nocreate_userorcreate_superuseruntil you write aUserManagerthat supplies them. Skip it andmanage.py createsuperuserfails, because the command callscreate_superuseron the model's default manager.
- Forgetting
USERNAME_FIELDandREQUIRED_FIELDS. When email replaces username as the login identifier,USERNAME_FIELD = "email"tells the auth backend what to look users up by, andREQUIRED_FIELDStellscreatesuperuserwhat else to prompt for. Omit them and superuser creation asks the wrong questions or the login silently never matches.
- Leaving
usernamein place on an email-first model. If email is the real identity but a nullable, non-uniqueusernamelingers, you get a half-migrated model where two records can share blank usernames and the login field is ambiguous. Decide which field is the identity and constrain it accordingly.
- Lowercasing the whole email address, or not normalizing it at all. No normalization means
Ada@x.comandada@x.combecome two accounts. Lowercasing the entire string, as the example does, over-normalizes: only the domain is case-insensitive. UseBaseUserManager.normalize_email, which lowercases just the part after the @.
- Enforcing uniqueness in Python instead of the database. A pre-save
exists()check or a scan through existing rows loses every race: two requests check at the same instant, both see nothing, both insert. Putunique=Trueon the field so the database rejects the second write, and catch the resultingIntegrityError.
Best Practices
- Create a custom user model on the first day of every project, even an empty one. A bare
class User(AbstractUser): passplusAUTH_USER_MODEL = "accounts.User"costs nothing now and preserves your freedom to add fields later without the migration nightmare. This one habit removes the entire risk this lesson describes.
- Set
AUTH_USER_MODELbefore you run the first migration. Treat it as part of initial project setup, alongside the database configuration, not something to revisit. The keel goes down before the frames are cut.
- Reference the user through indirection, always. Foreign keys use the string
settings.AUTH_USER_MODEL; runtime code usesget_user_model(). Neverfrom django.contrib.auth.models import User. This keeps the whole codebase swap-safe.
- Extend
AbstractUserfor ordinary additions; reserveAbstractBaseUserfor changing the identity itself. Most projects only need a phone number or a flag, andAbstractUserhands over the rest. Rebuild fromAbstractBaseUseronly when email-as-login or a different identity scheme demands it.
- Give every
AbstractBaseUseraUserManagerwithcreate_userandcreate_superuser. The manager is where email normalization, uniqueness, and the id-issuing logic belong, mirroring the stand-in above. Without it,createsuperusercannot work.
- Enforce uniqueness with a database constraint and normalize in the manager.
unique=TrueplusBaseUserManager.normalize_email(domain-only lowercasing) gives you correctness under concurrency and one canonical form for lookups.
- Declare
USERNAME_FIELDandREQUIRED_FIELDSwhenever the login identity is not the default username. These two attributes are what wire the auth backend andcreatesuperuserto the field you actually log in with.
- Keep authentication logic out of the model. Hash passwords with
set_password, verify withcheck_password, and let the permissions framework carry authorization. The user model's job is to describe fields; how identity is proven is a separate concern.
Practice Exercises
- Add a custom user model to an empty project. Starting from a fresh app called
accounts, writeclass User(AbstractUser)with one extra field,phone = models.CharField(max_length=20, blank=True), setAUTH_USER_MODEL = "accounts.User"in settings, then make and run the initial migration. Confirm thatcreatesuperuserstill succeeds and that the new column exists on the user table.
- Turn the stand-in into email-as-login. Modify the
UserManagerstand-in so the identity is email rather than a separate username. Extendcreate_userto reject a missing email and to store a stand-in password verifier (reuse the toy digest idea from the auth-system lesson), and add acheck_login(mgr, email, password)function that returns True only when the account exists, is active, and the verifier matches. Print results for a correct login, a wrong password, and an unknown address.
- Audit for dangling foreign keys. Given a
MODELSlist of(name, target)pairs like the one in Technical Depth, writeaudit(models, user_model)that returns the names whose target is notsettings.AUTH_USER_MODEL, then print asafe X/Ysummary. Extend it to also report, separately, any model whose target is the literalauth.User, since those are the hard-coded relations most likely to break on a swap.
- Fix the normalization bug. Rewrite
normalize_emailso it lowercases only the domain (the part after the last @) and leaves the local part unchanged. Then demonstrate the difference with two pairs:user@Example.comanduser@example.commust collapse to one canonical address (only the domain case differed), whileUser@example.comanduser@example.commust stay distinct (the local part differed, and that is case-sensitive). Explain in one sentence why Django normalizes email this way.