ContentsClose contents
Pre-release
Chapter 8 · Settings, environments, dependencies, and GitCHAPTER 08

Complete six-part pre-release for review. The project reads its secret key through python-decouple, locks its dependencies, and has its first Git commit, kept on your own computer until Chapter 34.

Working towards: First Otahque page (Chapter 9). Django answers a request with a page written for Otahque. All milestones

CHAPTER EIGHT

Settings, environments, dependencies, and Git

Stage 1: Requirements and first project (Chapters 1 to 8)

Prerequisites: Chapters 4, 6, and 7, and the verified Chapter 7 project with both system checks passing

What you’ll build: the same Otahque project made reproducible and safe to record: locked dependencies, settings that take their secrets from the environment, and a first Git commit that contains no secret.

Why This Matters

Our project works, but only on one computer and only as long as nothing goes wrong. Imagine Sam asks a second organizer to help with Otahque and hands over a copy of the folder. Three problems travel with it. The secret key that Django uses to sign values sits in config/settings.py, so everyone who receives the folder receives the key. Debug mode is switched on in the same file, with nothing to switch it off on a computer that should never show detailed error pages. And Chapter 6 pinned Django alone, so the packages Django itself needs could arrive in different versions on the second computer.

There is also no record of change. When something broke in Chapters 6 and 7, our recovery advice was to compare the folder with a fresh copy, because there was no history to look back through. That works for two chapters. It will not work for the next sixty, when every chapter changes files that earlier chapters wrote.

These problems share one question: which parts of the project are the same everywhere, and which belong to the place where it runs? This chapter answers it in three steps. It separates configuration from code, so each computer supplies its own secret key and debug mode. It records the project’s dependencies, so every computer installs exactly the same versions. Then it starts a history of the project with Git, taking care that no secret is ever written into that history.

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

  • explain how Django finds and loads its settings, and which settings must differ between environments;
  • read settings from environment variables with safe defaults, and supply local values from a file that is never shared;
  • distinguish declaring, locking, and installing dependencies, and turn the project into a uv project with a lock file;
  • describe Git’s working tree, staging area, and commits, and keep secrets and generated files out of the history;
  • make and check the project’s first commit, and recover from common mistakes without losing work.

This chapter prepares the project for change; it adds no Otahque behaviour. A separate production configuration waits for Chapters 62 and 63, when there is a production server to configure. Online repositories, automated checks on every change, and team branching wait for Chapters 34 and 64. Migrations stay unapplied, and the first Otahque page arrives in Chapter 9.

PAGE 001

What You Need to Know

One project, several environments

An environment is the place where the project runs, together with everything it runs with: the computer, the Python interpreter, the installed packages, and the configuration values it is given. So far we have had exactly one, your computer. Soon there will be more. Chapter 9 starts running automated tests, Chapter 34 runs them automatically on a separate machine, and Chapter 63 puts Otahque on a production server that members reach over the internet.

The aim is that the code is the same in every environment, while a small set of values differs. If each computer carries its own edited copy of the code, a change made on one is easily lost on another, and nobody can say which copy is right. Table 8.1 sorts the parts of our project into the two kinds.

Table 8.1 — What stays the same and what changes between environments
Part of the project Same everywhere? Where it will live
Our code: settings.py, the events app, manage.py Yes Recorded in Git
Declared dependencies and their exact locked versions Yes pyproject.toml and uv.lock, recorded in Git
Python version Yes .python-version, recorded in Git
Secret key No: each environment has its own Supplied by the environment
Debug mode No: on only for local development Supplied by the environment
Allowed host names No: each server has its own names Supplied by the environment
Installed packages in .venv Rebuilt on each computer from the lock Not recorded
Local database file Each computer has its own Not recorded
At the top, one card of files recorded once in Git: our code, settings.py, pyproject.toml, uv.lock, and .python-version. Arrows labelled same code lead down to three environments. Your computer has its own ignored .env file with its own key and debug mode on. A teammate’s computer has a different .env with a different key. Production, dashed because it arrives in Chapters 62 and 63, gets its key, debug off, and real host names from the hosting platform.
Figure 8.1 — One codebase in every environment; each environment supplies its own values.

The rows marked “No” are configuration. The rest of this part explains how Django reads configuration, which values are dangerous to share, how a program receives values from outside its code, and how the shared parts, code and dependencies, are recorded.

Que. 1 Chapter 32 moves Otahque to a PostgreSQL database, which needs a password. Which kind of value is that password, and where should it live?

Flip to check your answerFold answer back

Answer. It is configuration that differs between environments, and it is also a secret. Each environment would have its own database and its own password, supplied by that environment rather than written into settings.py. If the password were in the code, everyone who could read the code could reach the database.

How Django finds its settings

Every Django command starts by finding its settings module. Open manage.py and read the line that mentions settings; change nothing:

os.environ.setdefault(
    'DJANGO_SETTINGS_MODULE', 'config.settings'
)

DJANGO_SETTINGS_MODULE names the settings module as a dotted import path, the form Chapter 7 used in INSTALLED_APPS. config.settings means the file config/settings.py. The setdefault call sets the name only if it has not been set already, so a value supplied from outside the program would win. We will meet that idea, values supplied from outside, again shortly.

A settings module is ordinary Python. Django imports it once, when a command or the server starts, and runs it from top to bottom. Two rules follow from how Django reads the result. Only names written entirely in capital letters count as settings. And any setting the file does not mention keeps Django’s built-in default value.

Under the Hood: How Django loads settings

from django.conf import settings does not import your file straight away. It gives you a stand-in object, LazySettings, defined in django/conf/__init__.py. The first time code reads a setting, the stand-in looks up DJANGO_SETTINGS_MODULE and builds a Settings object. That object first copies every capitalized name from Django’s defaults in django/conf/global_settings.py, then imports your module and copies every capitalized name from it, replacing the defaults it names. Lowercase names are skipped. Because this happens once, at the first read, an error inside settings.py stops a command as it starts, and a change to the file takes effect the next time a command or the server starts.

Django can show the result of that merge. The diffsettings command prints each setting whose value differs from Django’s default. We do not need it in our build steps, but one detail of its output matters here. Run it beside manage.py, in PowerShell, a macOS shell, or Linux/WSL Bash:

uv run --no-project --python .venv python manage.py diffsettings

Expected result, shortened to a few of its lines:

DEBUG = True
...
ROOT_URLCONF = 'config.urls'  ###
SECRET_KEY = 'django-insecure-(your own key)'
...

Settings marked ### have no default in Django at all. The line to notice is SECRET_KEY: where this listing shows a placeholder, your terminal shows your own key in full, because so far it is just text in a file. Anything that prints your settings prints your secrets, so never paste this output into a public question or issue report.

Que. 2 A teammate adds site_name = 'Otahque' to settings.py, then reads settings.site_name in Django’s shell and gets AttributeError: 'Settings' object has no attribute 'site_name'. Why?

Flip to check your answerFold answer back

Answer. Django copies only names written entirely in capital letters from the settings module. site_name is an ordinary lowercase variable, so Django ignores it. Naming it SITE_NAME would make it a setting. Even then, it is better to choose a name that cannot clash with one of Django’s own settings.

Three settings that must differ

The file generated in Chapter 6 marks two of its lines with SECURITY WARNING comments, and a third line depends on them. These three settings are the ones that are dangerous to share between environments. Table 8.2 summarizes them.

Table 8.2 — The three settings that must differ between environments
Setting What it does Generated value Risk if shared
SECRET_KEY Signs values that Django must later trust, such as session data and password reset links A fixed string starting django-insecure- Anyone who knows it can create values that Django accepts as genuine
DEBUG Shows detailed error pages with code, local values, and settings True Error pages reveal how the site works to every visitor
ALLOWED_HOSTS Lists the host names this site will answer to [] (empty) Empty with debug off refuses every request; a wildcard accepts forged host names

The secret key needs the most care. “Signs” means that Django attaches a code to a value, worked out from the value and the key, so that a changed value can be detected later. Chapter 28 shows this with sessions. The protection holds only while the key stays secret. The key generated in Chapter 6 begins with django-insecure-, Django’s reminder that it was created for local development and written straight into a file. Nobody else knows yours yet, but anything recorded in a shared history stops being secret, and the book’s reference copy uses a key printed on its pages, which was never secret at all. So this chapter replaces the key before Git records anything.

Debug mode is the reason Django could show us its helpful error pages in Chapters 6 and 7. Those pages include parts of our code and settings, which is exactly what a developer needs and exactly what a visitor must never see. The Django deployment checklist states plainly that debug must never be enabled in production.

ALLOWED_HOSTS explains a small mystery: our list is empty, yet the development server answered 127.0.0.1. While debug is on and the list is empty, Django quietly allows the local names localhost, 127.0.0.1, and [::1]. Turn debug off, and that allowance disappears.

Que. 3 You switch DEBUG to False on your computer, leave ALLOWED_HOSTS empty, and try to start the development server. What do you expect, and why?

Flip to check your answerFold answer back

Answer. The server refuses to start. With debug off, Django no longer allows the local names automatically, so an empty list would refuse every request; runserver reports CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False. Setting debug and allowed hosts belongs together, which is why both move out of the code in this chapter.

Values supplied from outside the code

New Concept: environment variable

What problem exists? Each environment needs its own secret key and its own debug setting, but we want the same settings.py everywhere. The values must reach the program without being written into its code.

What did people do before? Many projects edited settings.py on each server by hand, or kept an extra settings file on each computer that was never shared and imported it at the end. Both meant several versions of the code drifting apart, and the extra file was easily lost or accidentally shared.

What is an environment variable? A named text value that the operating system gives a program when it starts. A program started from a terminal receives a copy of that terminal’s variables. Python reads them through os.environ, which behaves like a dictionary.

Why environment variables? Every operating system and every hosting platform supports them, so the same code can run anywhere while each place supplies its own values. Django’s deployment checklist reads the secret key this way.

Now let’s use it.

This experiment changes nothing in the project. It sets a variable for the current terminal only, then reads it from Python. In PowerShell, in otahque/:

$env:OTAHQUE_GREETING = 'hello'
uv run --no-project --python .venv python -c "
import os
print(os.environ['OTAHQUE_GREETING'])
print(os.environ.get('OTAHQUE_MISSING', 'no value'))
"

In a macOS shell or Linux/WSL Bash, in otahque/:

export OTAHQUE_GREETING=hello
uv run --no-project --python .venv python -c "
import os
print(os.environ['OTAHQUE_GREETING'])
print(os.environ.get('OTAHQUE_MISSING', 'no value'))
"

Expected result in either shell:

hello
no value

The two lookups behave differently, and the difference matters for settings. Square brackets demand the value: os.environ['OTAHQUE_MISSING'] would stop the program with KeyError. get() returns the default we supply when the variable is missing. Use brackets for a value the program must never run without, such as the secret key, and get() with a safe default for the rest. Remove the experiment’s variable afterwards: Remove-Item Env:OTAHQUE_GREETING in PowerShell, or unset OTAHQUE_GREETING in Bash.

Every environment variable is text. That catches many beginners out: bool('False') is True in Python, because any non-empty string counts as true. A setting such as debug mode must therefore compare the text with an exact expected value, rather than trusting Python to convert it.

A file of local values

Typing variables into every new terminal is tedious and easy to forget. A .env file holds them instead: a plain-text file of NAME=value lines, kept beside manage.py. Python does not read it by itself, so our settings will use a small library to read it. Because the file holds this computer’s secret key, it is never shared or recorded. A companion file, .env.example, lists the same names with harmless placeholder values, so a teammate can see which variables to provide.

New Tool: python-decouple

What problem exists? settings.py needs this computer’s values from .env, and real environment variables must still be able to supply them on other computers. Python reads environment variables but not .env files.

What did people do before? Projects wrote a small reader of their own, like the one in How We Build It, or asked everyone to set the variables by hand in every new terminal.

What is python-decouple? A small library whose config() function looks up a name in the environment variables first, then in a .env file that it finds by searching upward from the folder of the code that calls it, and finally in a default that you supply. It can also convert the text it finds, for example into a list.

Why python-decouple? It does one job, works the same on every platform, and leaves the choice of safe defaults to us. It is not specific to Django, so the same habit works in any Python project. We add it to the project in How We Build It.

Now let’s use it.

Two details of the file’s format matter. python-decouple reads each value exactly as written, with one convenience: a pair of matching quotes around a value is removed. It does not treat a # after a value as a comment, so in DJANGO_DEBUG=True # local, the value is the whole text True # local. Other programs that read .env files are less literal: some treat $ as the start of another variable’s name, and Django’s generated keys can contain $. So we always write the secret key inside single quotes, which stop those readers from changing it, and we put comments on lines of their own.

In practice: replacing a key after a laptop is lost

Situation. Later, an organizer who looks after Otahque’s production server loses a laptop that held a copy of the production values.

Application. Because the secret key lives in the environment rather than the code, the response is to generate a new key and give it to the server, with no change to the code.

Consideration. Replacing the key ends signed sessions and invalidates outstanding password reset links. Django’s SECRET_KEY_FALLBACKS setting can keep them working during a planned change of key, but not here: a key listed there still verifies, so it would stay useful to whoever has the laptop. Chapters 28 and 59 return to keys and signing.

Que. 4 Which of these two lines is safer for reading debug mode, and why? DEBUG = bool(os.environ.get('DJANGO_DEBUG')) or DEBUG = os.environ.get('DJANGO_DEBUG') == 'True'.

Flip to check your answerFold answer back

Answer. The second. In the first, any non-empty text turns debug on, including False and no. The second turns it on only for the exact text True, and leaves it off when the variable is missing, so a forgotten variable fails safe.

Dependencies: declared, locked, and installed

New Tool: uv projects

What problem exists? Chapter 6 installed Django==6.1.2, and uv quietly installed asgiref and sqlparse with it, plus tzdata on Windows, because Django needs them. Nothing records their versions. A teammate installing next month could receive newer ones, and “it works on my computer” would stop being a guarantee.

What did people do before? A common habit was pip freeze > requirements.txt, a snapshot of whatever one computer happened to have installed, including packages nobody chose deliberately, and recorded for that computer’s operating system only. Many projects recorded nothing at all.

What is a uv project? A folder that uv manages through two files. pyproject.toml declares what the project needs: its Python version and its direct dependencies. uv.lock records the exact version of every package uv chose to satisfy that declaration, with checksums, for every supported operating system. The .venv/ folder is the installed result on one computer.

Why uv projects? We already use uv to install Python and create environments, so nothing new needs installing. Before every uv run, uv brings the lock up to date with the declaration and .venv/ up to date with the lock, so the three agree whenever a command runs. That update happens quietly, so uv lock --check exists to report a lock that would change, without changing it.

Now let’s use it.

Two words help here. A direct dependency is a package our project chose, such as Django. A transitive dependency is one that arrives because a direct dependency needs it. Ask uv what Django requires, beside manage.py, in PowerShell, a macOS shell, or Linux/WSL Bash:

uv pip show --python .venv django

Expected result on Windows, shortened:

Name: django
Version: 6.1.2
...
Requires: asgiref, sqlparse, tzdata
Required-by:

On macOS and Linux, tzdata is not listed, because Django asks for it only on Windows. So far, Django is our only direct dependency, and the three packages it requires are transitive. How We Build It adds a second direct dependency, python-decouple. A good record pins both kinds. Figure 8.2 shows how the three parts of a uv project relate, and why two computers that start from the same lock end up with the same packages.

Three numbered cards from left to right. 1, pyproject.toml, declares Django 6.1.2, python-decouple 3.8, and Python 3.14.9 or later. An arrow labelled uv lock leads to 2, uv.lock, which records six exact versions with checksums for every operating system. An arrow labelled uv sync leads to 3, .venv on your computer, the installed packages matching the lock. A second arrow from uv.lock, also labelled uv sync, leads to a teammate’s .venv with the same packages. A purple card says uv run brings the lock and .venv up to date before each command, and a note says the two files are recorded in Git and each .venv is rebuilt on its own computer.
Figure 8.2 — The declaration states what we need, the lock records exactly what that means, and each environment is installed from the lock.

The lock is written by uv, not by hand. We edit the declaration, usually through commands such as uv add, and uv updates the lock to match. The lock covers every operating system at once: for example, Django needs tzdata only on Windows, and the lock records that condition, so a Linux computer installing from the same lock simply skips it.

Prefer a requirements.txt file?

Some hosting platforms and older tools expect a requirements.txt file rather than a lock. We do not keep one by hand, because it would be a second record that can disagree with the first. If a tool needs one later, uv can produce it from the lock with uv export, so uv.lock stays the single source.

Que. 5 Which of pyproject.toml, uv.lock, and .venv/ would you change by hand, and which should be recorded in Git?

Flip to check your answerFold answer back

Answer. Only pyproject.toml is meant to be edited by people, directly or through uv add. uv.lock is written by uv and should never be edited by hand. .venv/ is rebuilt from the lock on each computer and is never edited or recorded. Both files, pyproject.toml and uv.lock, are recorded in Git, so every computer installs the same versions.

Recording history with Git

New Tool: Git

What problem exists? We have no record of how the project reached its current state. When something breaks, we cannot see what changed, and undoing a mistake means comparing folders by eye.

What did people do before? Copies of the whole folder with names such as otahque-final and otahque-final-2, or archives sent back and forth. Nobody could tell which copy was current or what differed between them.

What is Git? A version control system: a tool that records snapshots of a project’s files, called commits, each with an author, a date, and a message saying why. The history lives in a hidden .git/ folder inside the project, on your computer. An online copy is optional and can be added later.

Why Git? It is the standard tool for recording code history, it works without a network, and every hosting platform and team workflow later in the book builds on it. From this chapter on, each chapter ends with a commit.

Now let’s use it.

Git keeps files in three places, shown in Figure 8.3. The working tree is the project folder as you see and edit it. The staging area holds the changes you have chosen for the next commit; git add puts them there. The history holds the commits; git commit turns the staged changes into a new one. The extra step between editing and committing is deliberate: it lets you review exactly what will be recorded before it is recorded.

Three numbered areas from left to right. 1, the working tree, holds the files you edit, such as settings.py and uv.lock. An arrow labelled git add leads to 2, the staging area, holding the changes chosen for the next commit. An arrow labelled git commit leads to 3, the history, a chain of commits. Below the working tree, a red card lists .env, .venv, db.sqlite3, and __pycache__, kept out by .gitignore so that git add never picks them up.
Figure 8.3 — Changes move from the working tree through the staging area into the history; ignore rules keep chosen files out.

A file named .gitignore lists patterns for files Git should not offer to stage, such as .env, .venv/, and the local database. Two facts about the history explain why we write that file first. A commit is permanent: deleting a file in a later commit removes it from the working tree, but the earlier commit still contains it. And ignore rules apply only to files Git is not already recording, so adding a pattern later does not remove a file that was already committed. The safe order is therefore: remove the secret from the code, write the ignore rules, and only then let Git see the folder.

Que. 6 Someone commits .env, notices, deletes it, and makes a second commit. Is the secret key safe now?

Flip to check your answerFold answer back

Answer. No. The first commit still contains .env, and anyone with a copy of the history can read it. The key must be treated as exposed and replaced with a new one. Removing a file from earlier commits is possible with specialist tools, but replacing the key comes first, because copies of the history may already exist elsewhere.

Try it yourself

Here is the list of what the Otahque folder will contain by the end of this chapter: manage.py, config/settings.py, events/models.py, .python-version, pyproject.toml, uv.lock, .env, .env.example, .venv/, db.sqlite3, and __pycache__/ folders. Sort them into files Git should record and files it should ignore. Decide before reading the answer.

Que. 7 Which files belong in the history, and which should be ignored?

Flip to check your answerFold answer back

Answer. Record manage.py, config/settings.py, events/models.py, .python-version, pyproject.toml, uv.lock, and .env.example: they are the same in every environment, and the example file holds no real values. Ignore .env, because it holds this computer’s secret key; .venv/, because each computer rebuilds it from the lock; db.sqlite3, because each computer has its own local data; and __pycache__/, because Python regenerates those compiled files automatically.

PAGE 002

How We Build It

Starting point: the verified Chapter 7 project, with both system checks passing. Work in otahque/, the folder that contains manage.py, .venv/, config/, and events/. These steps change config/settings.py and add pyproject.toml, uv.lock, .env, .env.example, .gitignore, and Git’s hidden .git/ folder. The visible result: both system checks pass using .env, git log shows one commit, and git status reports nothing left to record. The development server shows the same welcome page as before; no Otahque page changes.

The Custom Way: a .env reader by hand

python-decouple will read .env for us, but it helps to see what such a reader has to do. Read this listing; do not add it to the project.

import os


def load_env(path):
    """Copy NAME=value lines from a file into os.environ."""
    with open(path, encoding='utf-8') as lines:
        for line in lines:
            line = line.strip()
            if not line or line.startswith('#'):
                continue
            name, _, value = line.partition('=')
            if len(value) > 1 and value[0] == value[-1] == "'":
                value = value[1:-1]
            os.environ.setdefault(name.strip(), value)

It skips blank lines and comments, splits each line at its first =, and removes a pair of surrounding single quotes. setdefault, which we met in manage.py, means a variable already set in the terminal wins over the file. That is close to how python-decouple reads a .env file, and decouple keeps the same rule about the terminal. What decouple adds is the rest of the job. It finds the file by searching upward from the folder of the code that calls it, so config/settings.py finds the .env beside manage.py whichever folder the terminal is in. Each lookup states what happens when a name is missing: use a default, or stop with an error. It converts text into other types, such as lists. And many projects use and test it, so we do not maintain a reader of our own.

The Django Way: settings, lock, and history

Step 1: Make the folder a uv project

Common Error: running uv init without --bare

In a folder that already holds a project, plain uv init adds more than we want: a README.md, a src/ folder, a .gitignore, and a Git repository, and it copies your Git name and email into pyproject.toml if Git knows them. Type --bare exactly. If you have already run the plain command, Table 8.4 shows how to recover.

Two commands turn the folder into a uv project. In PowerShell, a macOS shell, or Linux/WSL Bash, beside manage.py:

uv init --bare --name otahque
uv add "Django==6.1.2" "python-decouple==3.8"

--bare writes only pyproject.toml, and --name gives the project its name, which otherwise comes from the folder. uv add records Django and python-decouple as dependencies with their exact versions, works out every package those versions need, writes them to uv.lock, and makes .venv/ match. Our environment already holds Django and its dependencies from Chapter 6, so uv installs only python-decouple. Expected result:

Initialized project `otahque`
Resolved 6 packages in ...
Prepared 1 package in ...
Installed 1 package in ...
 + python-decouple==3.8

The timings differ on every run, and the Prepared line is absent if uv already has the package. The six resolved packages are Django, its three dependencies, python-decouple, and our project itself. Open the new file:

[project]
name = "otahque"
version = "0.1.0"
requires-python = ">=3.14.9"
dependencies = [
    "django==6.1.2",
    "python-decouple==3.8",
]

requires-python comes from the .python-version file of Chapter 6 and states the oldest Python this project accepts. dependencies lists our direct dependencies; uv writes package names in lower case. Chapter 53 changes the Django pin to 6.1.3, a security release. Leave uv.lock closed: it is long, written by uv, and never edited by hand. To see what it records, ask uv for the dependency tree:

uv tree

Expected result on Windows:

Resolved 6 packages in ...
otahque v0.1.0
├── django v6.1.2
│   ├── asgiref v3.13.0
│   ├── sqlparse v0.6.0
│   └── tzdata v2026.5
└── python-decouple v3.8

On macOS and Linux, the tzdata line is absent, because the tree shows what this computer needs. From now on, Django commands are shorter. Because the folder is a uv project, uv run finds .venv/ by itself and brings the lock and the environment up to date before every command. Chapter 6’s --no-project --python .venv told uv to ignore any project, and we no longer need it. In any of the three shells:

uv run python manage.py check

Expected result:

System check identified no issues (0 silenced).

Step 2: Read the three settings from the environment

Open config/settings.py. The first change goes at the top, after the long comment at the start of the file. Add two import lines, so that the imports read:

from pathlib import Path

from decouple import Csv, UndefinedValueError, config
from django.core.exceptions import ImproperlyConfigured

config is python-decouple’s lookup function, Csv turns comma-separated text into a list, and UndefinedValueError is the error config raises when a name has no value and no default. ImproperlyConfigured is the exception Django raises when its configuration is wrong; we met it in Chapter 7, when a repeated app label stopped loading. The second change replaces a block lower down. Find the lines from # Quick-start development settings to ALLOWED_HOSTS = [], just above # Application definition, and replace them with this:

# Values that differ between environments come from the
# environment or the .env file. .env.example lists them.

# SECURITY WARNING: keep the secret key used in production
# secret! There is no default: a missing key stops Django.
try:
    SECRET_KEY = config('DJANGO_SECRET_KEY')
except UndefinedValueError:
    raise ImproperlyConfigured(
        'Set DJANGO_SECRET_KEY; see .env.example.'
    ) from None

# SECURITY WARNING: don't run with debug turned on in
# production! Debug is on only for the exact text True.
DEBUG = config('DJANGO_DEBUG', default='') == 'True'

# Host names separated by commas, such as:
# otahque.example,www.otahque.example
ALLOWED_HOSTS = config(
    'DJANGO_ALLOWED_HOSTS', default='', cast=Csv()
)

Each setting follows a rule from What You Need to Know. config() without a default behaves like square brackets: it demands the value, and raises UndefinedValueError when the name is in neither the environment nor .env. We catch that and raise ImproperlyConfigured with a message that names the fix. from None leaves the first error out of the report, so its last line is our instruction. With default=, config() behaves like get(). Debug mode is on only when the value is exactly True, so a missing or misspelled value fails safe. decouple could convert the text for us with cast=bool, but that also accepts yes, on, and 1; comparing with one exact spelling keeps the rule simple. cast=Csv() splits the host names at commas, and turns empty text into an empty list, which matches the generated ALLOWED_HOSTS = [].

Save the file and run the check again, still without any values:

uv run python manage.py check

This time Django refuses to start. The error report ends with ImproperlyConfigured and our message, Set DJANGO_SECRET_KEY; see .env.example. That is the safe failure we wanted: without a key of its own, the project stops, instead of starting with a key that other people know. Every command that needs the settings stops the same way until the next step.

Step 3: Give this computer its own values

Common Error: a comment after a value

If you add a note after a value in .env, such as DJANGO_DEBUG=True # local only, python-decouple reads the whole text as the value. Debug mode then stays off, and the development server refuses to start with no allowed hosts. Put each comment on a line of its own, starting with #.

This command generates a new key with the same Django function that startproject used in Chapter 6, and writes it into a new .env file. It is the same in PowerShell, a macOS shell, and Linux/WSL Bash; type it exactly, including the final double quote:

uv run python -c "
from django.core.management.utils import get_random_secret_key
key = repr(get_random_secret_key())
with open('.env', 'x', encoding='utf-8') as env:
    print('DJANGO_SECRET_KEY=' + key, file=env)
    print('DJANGO_DEBUG=True', file=env)
"

repr() returns the key wrapped in single quotes, which keeps it exact for the programs that commonly read .env. The 'x' mode creates the file only if it does not exist yet, so running the command a second time cannot replace your key; it stops with FileExistsError instead. The command prints nothing when it succeeds, and the key never appears in your terminal. Open .env to see its shape:

DJANGO_SECRET_KEY='(50 random characters)'
DJANGO_DEBUG=True

DJANGO_ALLOWED_HOSTS is left out: its default, an empty list, lets the development server answer the local names while debug is on. Now create .env.example beside it in your editor, with exactly these lines:

# Names this project reads. Create .env with the key command
# in Chapter 8, Step 3. Never record .env in Git.
DJANGO_SECRET_KEY=
DJANGO_DEBUG=True
# Host names separated by commas; leave empty locally.
DJANGO_ALLOWED_HOSTS=

This file names every variable and holds no real value, so it is safe to record. The key is empty on purpose: someone who copies this file to .env cannot end up running on a key printed in a book, because Django stops with The SECRET_KEY setting must not be empty. the first time the key is read. The system check does not read the key, so it passes until then. Run both checks again. The settings now find .env by themselves, so the commands are the same as in Step 1:

uv run python manage.py check
uv run python manage.py check events

Expected result, once for each command:

System check identified no issues (0 silenced).

Confirm that the values arrived as intended. This prints the key’s length, never the key itself:

uv run python manage.py shell -c "
from django.conf import settings
print(settings.DEBUG, settings.ALLOWED_HOSTS)
print(len(settings.SECRET_KEY))
"

Expected result:

12 objects imported automatically (use -v 2 for details).

True []
50

If the last line is not 50, the key was changed when .env was edited; Table 8.4 shows the fix. The development server works exactly as before. Start it, visit http://127.0.0.1:8000/, see Django’s welcome page, then stop it with Ctrl+C:

uv run python manage.py runserver

Every Django command reads .env through the settings, so none of them needs anything extra. A running server does not notice an edit to .env, though: its reloader watches Python files, so stop and start it after changing a value. One more rule from the Custom Way applies: a variable already set in your terminal wins over the file. If an experiment left DJANGO_DEBUG or DJANGO_SECRET_KEY set in your terminal, remove it, or open a new terminal.

Step 4: Install Git and tell it who you are

Check whether Git is installed, in any of the three shells:

git --version

Expected result: a line such as git version 2.51.0, possibly with a Windows suffix. This book was checked with Git 2.51; the commands in this chapter need version 2.28 or later. If the command is not found, install Git, then open a new terminal so that it can find the new program.

PowerShell, on Windows:

winget install --id Git.Git -e --source winget

macOS shell, which installs Apple’s command-line tools, including Git:

xcode-select --install

Linux or WSL Bash, on Debian or Ubuntu; other distributions use their own package manager:

sudo apt update
sudo apt install git

Every commit records its author’s name and email address. Ask Git what it already knows:

git config --global user.name
git config --global user.email

If both commands print a value, keep them and go on to Step 5. Otherwise, set them, replacing the examples with your own name and address:

git config --global user.name "Your Name"
git config --global user.email "you@example.com"

--global stores the values for every repository on this computer. The address becomes part of every commit, so if you later publish the history, consider the private address that most hosting services offer.

Common Error: Author identity unknown

If the identity is not set, git commit stops with Author identity unknown and suggests the two git config commands above. Nothing is lost: the staged changes wait. Set the identity and run the commit again.

Step 5: Write the ignore rules, then create the repository

Create .gitignore beside manage.py, with these lines:

# Local values, including this computer's secret key
.env

# The environment, rebuilt from uv.lock on each computer
.venv/

# Files Python regenerates automatically
__pycache__/
*.pyc

# This computer's local development database
db.sqlite3

Lines starting with # are comments. Table 8.3 explains each pattern.

Table 8.3 — What .gitignore keeps out of the history, and why
Pattern What it matches Why it is not recorded
.env The file of local values It holds this computer's secret key
.venv/ The environment folder; a trailing slash matches folders only It is rebuilt from uv.lock on each computer
__pycache__/ and *.pyc Compiled Python files Python regenerates them automatically
db.sqlite3 The local development database Each computer keeps its own data, and it may later hold personal data

A pattern matches whole names, so .env does not match .env.example, which we want recorded. Now create the repository:

git init -b main

Expected result, with your own folder’s path:

Initialized empty Git repository in .../otahque/.git/

-b main names the first line of history main. Teams work with several such lines, called branches, which Chapters 34 and 64 introduce. Before staging anything, look at what Git sees:

git status --short

Expected result:

?? .env.example
?? .gitignore
?? .python-version
?? check_environment.py
?? config/
?? events/
?? manage.py
?? pyproject.toml
?? uv.lock

?? marks a file Git is not recording yet, and a folder appears once for all its files. Neither .env nor .venv/ appears. Ask Git which rule keeps each one out:

git check-ignore -v .env .venv db.sqlite3

Expected result:

.gitignore:2:.env	.env
.gitignore:5:.venv/	.venv
.gitignore:12:db.sqlite3	db.sqlite3

Each line names the ignore file, the line number, the pattern, and the path. Git reports db.sqlite3 even if the file does not exist yet, because the rule is ready for it.

Step 6: Make the first commit

Common Error: staging .env

If .env appears in a status listing marked A, it has been staged. Remove it from the staging area with git rm --cached .env, then check the spelling in .gitignore. --cached matters: it removes the file from what Git will record but leaves it on your disk. Without --cached, Git refuses here; forcing it with -f would delete the file from your disk. If other unwanted files are staged too, Table 8.4 shows how to start the staging again.

Stage everything that is not ignored, then review the list:

git add .
git status --short

Expected result, shortened:

A  .env.example
A  .gitignore
A  .python-version
...
A  manage.py
A  pyproject.toml
A  uv.lock

A marks a file staged to be added. Read the whole list: it should hold 19 files, including the seven in events/ and five in config/, and no .env, .venv/, or db.sqlite3. To read the staged changes line by line, run git diff --cached, and press q to leave it. On Windows, git add may first print warnings such as LF will be replaced by CRLF the next time Git touches it. They are about line endings, the invisible characters that end each line, which Windows and other systems write differently. Git for Windows usually adjusts them when it writes files back; your files’ content is unaffected, and nothing needs fixing. Record the commit:

git commit -m "Prepare settings, lock, and Git"

Expected result, shortened; your commit’s short identifier and line count differ:

[main (root-commit) ccd5917] Prepare settings, lock, and Git
 19 files changed, ... insertions(+)
 create mode 100644 .env.example
...

Look at the history and the working tree:

git log --oneline
git status

Expected result:

ccd5917 Prepare settings, lock, and Git
On branch main
nothing to commit, working tree clean

Finally, confirm that no secret was recorded. Both commands should print nothing: the first lists .env only if Git records it, and the second searches every recorded file for the start of Chapter 6’s key.

git ls-files .env
git grep -n "django-insecure"

When something goes wrong

Table 8.4 lists the problems this chapter’s steps can produce. Each recovery keeps your work: it corrects one file, one setting, or the staging area, or renames a file instead of deleting it.

Table 8.4 — Chapter 8 problems and non-destructive recovery
Symptom Likely cause Recovery
A command ends with ImproperlyConfigured: Set DJANGO_SECRET_KEY; see .env.example. .env is missing, has another name, or sits where the search does not reach, such as events/, or the variable name in it is misspelled Check that .env sits beside manage.py and that one line starts DJANGO_SECRET_KEY=. If .env does not exist, create it with Step 3
FileExistsError: [Errno 17] File exists: '.env' Step 3 has already created .env Keep the existing file and check its key length with the shell command in Step 3
The key length is not 50 The key was changed while .env was edited by hand Rename .env to .env.old, run Step 3 again, and delete .env.old once both checks pass. .gitignore does not cover .env.old, so do not stage files until it is gone
ImproperlyConfigured: The SECRET_KEY setting must not be empty. The key line in .env is empty, for example after copying .env.example Rename .env to .env.old, run Step 3, and delete .env.old once both checks pass. .gitignore does not cover .env.old, so do not stage files until it is gone
CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False. DJANGO_DEBUG is missing or not exactly True, for example true, or a comment follows the value Correct the line in .env to DJANGO_DEBUG=True, with any comment on a line of its own, and run the command again
error: Project is already initialized, or new README.md, src/, and .git/ after uv init Plain uv init ran instead of uv init --bare Remove only the items uv just created: README.md, src/, .gitignore, .git/, and pyproject.toml. Then run Step 1 again
error: The lockfile at uv.lock needs to be updated, but --check was provided. pyproject.toml was edited without updating the lock Run uv lock, then review both files before committing. Never edit uv.lock by hand
'git' is not recognized, or git: command not found Git is not installed, or the terminal opened before installation Install Git with Step 4, then open a new terminal
Author identity unknown Git does not know your name and email Set both with git config --global, then run the commit again
.env appears as A in git status --short The .env line in .gitignore is misspelled git rm --cached .env, then correct the spelling in .gitignore
Many files appear as A, including .env, db.sqlite3, or .pyc files git add . ran before .gitignore existed Write .gitignore, run git rm -r --cached . to empty the staging area, then run git add . and read the list again. Your files stay on disk
git ls-files .env prints .env after a commit .env was recorded in a commit git rm --cached .env and commit. Then treat the key as exposed: rename .env to .env.old, run Step 3, confirm both checks, then delete .env.old before staging anything
Warnings that LF will be replaced by CRLF Git for Windows adjusts line endings Nothing to fix; the warnings do not change your files' content

A recorded secret needs a new key even after git rm --cached, because earlier commits still contain the old one. While the history exists only on your computer, the new key is enough. Once a history has been shared, removing a file from earlier commits needs specialist tools and the cooperation of everyone with a copy, which is why replacing the key always comes first.

For further reference, Django 6.1 documents settings at https://docs.djangoproject.com/en/6.1/topics/settings/, the deployment checklist at https://docs.djangoproject.com/en/6.1/howto/deployment/checklist/, and cryptographic signing at https://docs.djangoproject.com/en/6.1/topics/signing/.

PAGE 003

Verify Your Work

Automated tests begin in Chapter 9, once there is a page whose result we can assert. For now, run the checks in Table 8.5 from otahque/. Each one confirms a result of this chapter rather than repeating a step, and all of them must pass before Chapter 9.

Table 8.5 — Verification checklist for Chapter 8
Check Command or action Expected result
The lock matches the declaration uv lock --check Resolved 6 packages, with no error
The environment matches the lock uv sync --locked Resolved 6 packages; Checked 5 packages (4 on macOS and Linux)
The project starts with local values uv run python manage.py check, then the same with check events System check identified no issues (0 silenced). for each
The values arrived intact The shell command from Step 3 True [] on one line, then 50
Ignored files stay out git check-ignore -v .env .venv db.sqlite3 One rule from .gitignore for each path
The history holds one clean commit git status, then git log --oneline nothing to commit, working tree clean; one line ending Prepare settings, lock, and Git
No secret is recorded git ls-files .env, then git grep -n "django-insecure" No output from either command

The missing-key stop was shown in Step 2, and the mini-challenge shows it again in a copy that has no .env yet. If uv lock --check or uv sync --locked reports a change, something has edited pyproject.toml since Step 1: compare it with the listing in Step 1 before going further. If a Git check prints something unexpected, find its symptom in Table 8.4.

PAGE 004

Checkpoint: Quiz and Challenge

Quiz

Que. 8 Why does our settings.py stop with ImproperlyConfigured when the secret key is missing, instead of falling back to a default key?

Flip to check your answerFold answer back

Answer. A default key would be written in the code, so everyone who can read the code would know it, and a forgotten variable on a server would silently run with that shared key. Stopping with a clear message makes the mistake visible at once and names the fix.

Que. 9 A teammate’s .env contains DJANGO_DEBUG=yes. Is debug mode on? Why?

Flip to check your answerFold answer back

Answer. No. Our setting turns debug on only for the exact text True, so yes, true, and a missing variable all leave it off. That is deliberate: a mistake fails safe. With debug off and no allowed hosts, the development server then refuses to start, which tells the teammate to fix the line.

Que. 10 What is the difference between pyproject.toml and uv.lock, and which one do you change?

Flip to check your answerFold answer back

Answer. pyproject.toml declares what the project needs: its Python version and its direct dependencies. uv.lock records the exact version of every package that satisfies the declaration, for every operating system. We change the declaration, usually through uv add, and let uv rewrite the lock; the lock is never edited by hand. Both are recorded in Git.

Que. 11 You ran git add . before writing .gitignore, and .env is now staged. What do you run, and why does one option in the command matter?

Flip to check your answerFold answer back

Answer. .env is not the only problem: git add . also staged db.sqlite3 and the compiled Python files. Write .gitignore, run git rm -r --cached . to empty the staging area, then run git add . and read the list with git status --short. --cached removes files only from what Git will record and leaves them on your disk. Without it, Git refuses, and forcing it with -f would delete them. Because nothing has been committed yet, the key has not entered the history.

Que. 12 How does settings.py find .env, and what happens when the same variable is also set in your terminal?

Flip to check your answerFold answer back

Answer. python-decouple’s config() searches for .env starting in the folder of the file that calls it, config/, and then in each parent folder, so it finds the file beside manage.py whichever folder the terminal is in. It checks environment variables first, so a value already set in the terminal wins over the file. A leftover value from an experiment can therefore override .env until you remove it or open a new terminal. The upward search has a similar catch: a stray .env in a folder above the project supplies its values without warning, so if a check passes when you expected a refusal, look for one.

Mini-Challenge

Prove that the project can be rebuilt on another computer from what Git records. Clone the repository into a new sibling folder, install the environment from the lock, give the copy its own key, and run both checks. Then confirm that the copy’s key differs from yours, without printing either key. Work it out before reading the model answer. Before you start, check that no otahque-clone/ folder exists beside otahque/; if one does, choose another new name and use it throughout.

Que. 13 What commands prove it, and what should each one show?

Flip to check your answerFold answer back

Answer. From the folder that contains otahque/, in PowerShell, a macOS shell, or Linux/WSL Bash, clone and install:

git clone otahque otahque-clone
cd otahque-clone
uv sync --locked

git clone prints Cloning into 'otahque-clone'... and done.; the copy has every recorded file and no .env or .venv/. uv sync --locked reports Creating virtual environment at: .venv, then installs the five locked packages on Windows, or four on macOS and Linux, each at its locked version. A warning that uv failed to hardlink files is harmless: it only means uv copied files from its cache instead of linking them. The copy has no .env yet, so the system check should refuse to run:

uv run python manage.py check

The error report ends with ImproperlyConfigured and the message Set DJANGO_SECRET_KEY; see .env.example. If it passes instead, a .env in a folder above is supplying the key; Que. 12 explains why. Now run Step 3’s key command inside otahque-clone/, followed by both checks:

uv run python manage.py check
uv run python manage.py check events

Each prints System check identified no issues (0 silenced). Compare the two files without printing them:

uv run python -c "
mine = open('.env', encoding='utf-8').read()
theirs = open('../otahque/.env', encoding='utf-8').read()
print(mine != theirs)
"

It prints True. The copy works with its own key, from recorded files alone: that is what this chapter set out to make possible. Return with cd ../otahque and delete otahque-clone/ when you have finished; it shares nothing with your project.

What We Learned

  • An environment is where the project runs and what it runs with; the code stays the same everywhere, and a few values, the configuration, differ.
  • Django finds its settings through DJANGO_SETTINGS_MODULE, reads them once over its own defaults, and counts only capitalized names.
  • The secret key, debug mode, and allowed hosts must differ between environments; ours now come from environment variables, with no default key and debug off unless asked for.
  • A .env file supplies one computer’s values, read by python-decouple from settings.py; it is never recorded, while .env.example documents the names.
  • pyproject.toml declares, uv.lock pins every package for every platform, and .venv/ is rebuilt from the lock on each computer.
  • Git records commits from the staging area; .gitignore written first, a fresh key, and a review of the staged list kept every secret out of the first commit.

Key terms

Use Table 8.6 to explain configuration, dependencies, and history in your own words.

Table 8.6 — Key terms from Chapter 8
Term Meaning in this chapter
Environment Where the project runs, with its interpreter, installed packages, and configuration.
Configuration The values that differ between environments, such as the secret key and debug mode.
Settings module The Python module Django reads its settings from, named by DJANGO_SETTINGS_MODULE.
Environment variable A named text value the operating system gives a program when it starts.
.env file A plain-text file of one computer's NAME=value lines, read by python-decouple and never recorded.
python-decouple A library whose config() reads a value from the environment, then .env, then a default.
Secret key The value Django uses to sign data it must later trust; each environment needs its own.
Direct dependency A package the project chose itself, such as Django.
Transitive dependency A package installed because a direct dependency needs it, such as asgiref.
Lock file uv.lock: the exact version and checksums of every package, for every platform.
Repository A project folder whose history Git records, kept in the .git/ folder.
Working tree The project's files as you see and edit them.
Staging area The changes chosen for the next commit.
Commit A lasting snapshot of staged changes, with an author, a date, and a message.
Ignore rule A .gitignore pattern for files Git should not offer to stage.

Readiness checkpoint: explain which parts of the project are configuration and why; show that a missing secret key stops Django with your message; run both checks with this computer’s .env; show the key length of 50 without printing the key; explain what pyproject.toml and uv.lock each record; show one clean commit that contains no .env; and rebuild the project from Git in a sibling folder. Return to the relevant part if any result is missing.

Git Commit

This chapter’s commit was made in Step 6, so there is nothing new to record. The mini-challenge worked in a separate folder and changed nothing inside otahque/. Confirm it, in any of the three shells:

git status

Expected result:

On branch main
nothing to commit, working tree clean

From Chapter 9 onward, each chapter ends here with the same three moves: git status --short to see what changed, git add with the files that chapter names, and git commit after reading the staged changes with git diff --cached.

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 how it works underneath. L4 and L5 ask about decisions that later chapters build on, when Otahque gains automated checks and a production server: attempt them now, and return to them when you reach those chapters. Use the readiness checkpoint to decide whether to continue. If an answer is difficult, revisit its worked example and explain the result in your own words. L4 and L5 are extension questions, not a gate to the next chapter.

L1 (Junior): Why should a Django project’s secret key stay out of settings.py and out of Git?

What the interviewer is testing: Do you know what the secret key protects, and why recording it is the risk?

Flip to check your answerFold answer back

Perfect answer: Django uses the secret key to sign values it will later trust, such as session data, password reset links, and messages. Anyone who knows the key can create values that Django accepts as genuine. A key written in settings.py is known to everyone who can read the code, and once it is committed, every copy of the history contains it, even after a later commit deletes it. So each environment gets its own key, supplied from outside the code, and a key that has been exposed is replaced rather than hidden.

Table 8.7 — A key in the code compared with a key from the environment
Question Key written in settings.py Key supplied by the environment
Who can read it? Everyone with the code or its history Only whoever manages that environment
Same everywhere? Yes, one key for every copy No, each environment has its own
Replacing it means A code change and a new commit Changing one value where it is supplied
Recorded in Git? Yes, permanently No

Behind the scenes:

# dumps(value) serializes the value, then appends a signature
# computed from the value and SECRET_KEY (an HMAC).
# loads(token) recomputes the signature; if the value or the
# key differs, it raises BadSignature instead of returning it.

Code proof: in PowerShell, a macOS shell, or Linux/WSL Bash, beside manage.py:

uv run python manage.py shell -c "
from django.core import signing
token = signing.dumps({'member': 'sai'})
print(signing.loads(token))
def check(value, key=None):
    try:
        return signing.loads(value, key=key)
    except signing.BadSignature:
        return 'rejected'
print(check(token + 'a'))
print(check(token, key='another-key'))
"
12 objects imported automatically (use -v 2 for details).

{'member': 'sai'}
rejected
rejected

The signed value comes back intact; a changed token and a different key are both rejected.

Common mistakes:

  • Thinking the key encrypts data; it signs it, so anyone can still read a signed value.
  • Deleting the key in a later commit and assuming the history no longer holds it.
  • Sharing one key between development and production.

Follow-up the interviewer might ask:

  • “What happens to signed-in members when the key changes?”
  • “How would you replace a key without signing everyone out at once?”

L2 (Mid-Level): How do you make a Django project reproducible on a teammate’s computer?

What the interviewer is testing: Can you separate what is recorded from what each computer supplies, and prove the result?

Flip to check your answerFold answer back
Five numbered steps from top to bottom: clone the recorded files; install from the lock with uv sync --locked; create this computer’s own .env; run both checks with the local values; confirm that the lock is unchanged.
Figure 8.4 — From a recorded history to a working copy on another computer.

Perfect answer: Record everything that should be the same: the code, .python-version, pyproject.toml, and uv.lock, which pins every package and its checksums for every operating system. Keep out what each computer supplies: .venv/, the local database, and .env, with .env.example listing the names it needs. The teammate clones the repository, runs uv sync --locked, which fails rather than changing the lock, creates their own .env with their own key, and runs the system checks. If uv lock --check passes and the checks pass, both computers run the same versions with their own values.

Behind the scenes:

# one [[package]] table per package, for example:
#   name = "tzdata", version = "2026.5"
#   with the download URL, size, and sha256 checksum
# platform conditions sit on the dependency that needs them:
#   { name = "tzdata", marker = "sys_platform == 'win32'" }

Code proof: ask uv to show the lock as a list of exact pins:

uv export --format requirements-txt --no-hashes
Resolved 6 packages in ...
# This file was autogenerated by uv via the following command:
#    uv export --format requirements-txt --no-hashes
asgiref==3.13.0
    # via django
django==6.1.2
    # via otahque
python-decouple==3.8
    # via otahque
sqlparse==0.6.0
    # via django
tzdata==2026.5 ; sys_platform == 'win32'
    # via django

Every package, direct and transitive, has one exact version, and tzdata carries its Windows condition.

Common mistakes:

  • Recording .venv/ instead of the lock.
  • Pinning only the direct dependency, so transitive versions drift.
  • Sharing a .env file instead of documenting its names.

Follow-up the interviewer might ask:

  • “What is the difference between uv sync and uv sync --locked?”
  • “How would you upgrade one package without changing the others?”

L3 (Senior): How does Django find and load its settings, and what happens when a required value is missing?

What the interviewer is testing: Do you understand the lazy settings object, the merge over defaults, and where a configuration error appears?

Flip to check your answerFold answer back
Five numbered steps from top to bottom: manage.py names the settings module; the first read of a setting starts loading; Django copies its own default settings; it imports config.settings and copies the capitalized names; a missing key raises ImproperlyConfigured and the command stops.
Figure 8.5 — How a command finds, loads, and checks its settings.

Perfect answer: manage.py sets DJANGO_SETTINGS_MODULE to config.settings unless the environment already names a module. django.conf.settings is a lazy object: the first time anything reads a setting, it builds a Settings object by copying every capitalized name from django/conf/global_settings.py, then importing the named module and copying its capitalized names over them. The module runs top to bottom as ordinary Python, so our config() lookups, which read the environment and then .env, happen at that moment. A missing DJANGO_SECRET_KEY raises our ImproperlyConfigured during that import, so the command stops before it does any work. Settings are read once per process and should never be changed at runtime.

Behind the scenes:

# class LazySettings: on first attribute access, _setup()
#     reads os.environ['DJANGO_SETTINGS_MODULE']
#     and creates Settings(module_name)
# class Settings: copy UPPERCASE names from global_settings,
#     import_module(module_name), copy its UPPERCASE names

Code proof: show which module was loaded, and a default that our file never sets:

uv run python manage.py shell -c "
from django.conf import settings, global_settings
print(settings.SETTINGS_MODULE)
print(settings.DEFAULT_CHARSET, global_settings.DEFAULT_CHARSET)
"
12 objects imported automatically (use -v 2 for details).

config.settings
utf-8 utf-8

DEFAULT_CHARSET appears nowhere in our settings.py, yet it has a value: Django’s default, copied before our module was read.

Common mistakes:

  • Changing settings.DEBUG in code and expecting Django to behave differently.
  • Defining a lowercase name and expecting it to become a setting.
  • Importing application code into settings.py, which runs before apps are loaded.

Follow-up the interviewer might ask:

  • “How would you run one command with a different settings module?”
  • “Why fail at startup rather than when the key is first used?”

L4 (Staff): How would you design Otahque’s configuration for local development, automated checks, staging, and production?

What the interviewer is testing: Can you keep one codebase while making each environment’s differences explicit, few, and checked?

Flip to check your answerFold answer back
Five numbered steps from top to bottom: list the values that differ; name each one and make it required or give it a safe default; supply them from each environment; stop at startup if one is missing; run the deployment checks before each release.
Figure 8.6 — Designing configuration that is explicit, few, and checked.

Perfect answer: Keep one codebase and one lock for every environment, and treat the differences as a short, documented list: the secret key, debug mode, host names, and later the database, email, and storage settings. Give each value a name, and decide whether it is required, like the key, or has a safe default, like debug off. Local development reads a .env file; automated checks, staging, and production receive their values from the platform’s own store for secrets. Validate at startup so a missing value stops the process instead of half-working. Before each release, run Django’s deployment checks against the production values; Chapter 63 does this for Otahque. A separate production settings module becomes worthwhile when the structure differs, not merely the values, which is why the book waits for Chapters 62 and 63.

Behind the scenes:

# Checks are registered with tags. Those registered with
# deploy=True, such as most security checks, run only when
# check --deploy, or run_checks(include_deployment_checks=True),
# asks for them. They read the settings currently loaded.

Code proof: run the deployment checks against our local values, sorted by identifier:

uv run python manage.py shell -c "
from django.core import checks
found = checks.run_checks(include_deployment_checks=True)
for message_id in sorted(message.id for message in found):
    print(message_id)
"
12 objects imported automatically (use -v 2 for details).

mail.E001
security.W004
security.W008
security.W012
security.W016
security.W018
security.W020

Our local values fail these checks on purpose. W018 is debug mode, W020 the empty host list, and mail.E001 the console email backend, which only prints messages. The other warnings concern HTTPS settings. Production must clear each one, which Chapters 43 and 63 do.

Common mistakes:

  • One settings file per environment that copies everything, so the copies drift apart.
  • Defaults that are unsafe in production, such as debug on.
  • Secrets passed on the command line, where shell history and process listings keep them.

Follow-up the interviewer might ask:

  • “Where would you keep production secrets, and who can read them?”
  • “How do automated checks get a secret key without one being recorded?”

L5 (Lead): A secret key was committed and pushed to a shared repository. How do you lead the response?

What the interviewer is testing: Can you contain the exposure first, coordinate the clean-up, and prevent a repeat without blame?

Flip to check your answerFold answer back
Five numbered steps from top to bottom: treat the key as exposed; deploy a new key, with no fallback by default; stop tracking the file and agree with the team on the history; review activity during the exposure; add prevention and share a blame-free note.
Figure 8.7 — Responding to a recorded secret.

Perfect answer: Treat the key as exposed the moment it was pushed, because copies may already exist. First contain it: generate a new key and deploy it to every environment that used the old one, without listing the old key in SECRET_KEY_FALLBACKS. Everyone is signed out and outstanding password reset links stop working, and that is the price of closing the exposure: while the old key is listed, whoever holds it can still create values Django accepts. A fallback is for a planned change of a key that is still secret; using one here is a risk decision to state openly and keep short. Next, stop tracking the file with git rm --cached, and decide with the team whether to rewrite the shared history; that needs everyone with a copy to cooperate, so it never replaces replacing the key. Then review activity during the exposure, such as unexpected password resets. Finally, prevent a repeat: ignore rules written before the first commit, a review of staged files, and automated secret scanning when the project gains automated checks. Share a short, blame-free note on what happened and what changed.

Behind the scenes:

# Signer(key=None, fallback_keys=None) uses SECRET_KEY to sign
# and accepts a signature made with SECRET_KEY or any key in
# SECRET_KEY_FALLBACKS when verifying. New values are always
# signed with the current key.

Code proof: two demonstration keys, used only in this example, show what a fallback does:

uv run python manage.py shell -c "
from django.core import signing
old, new = 'old-key-for-demo', 'new-key-for-demo'
token = signing.dumps('sai', key=old)
print(signing.loads(token, key=new, fallback_keys=[old]))
try:
    signing.loads(token, key=new)
except signing.BadSignature:
    print('rejected without the fallback')
"
12 objects imported automatically (use -v 2 for details).

sai
rejected without the fallback

A value signed with the old key still verifies while the old key is a fallback, and stops verifying once the fallback is removed. That suits a planned change of key; for an exposed key, it is exactly the risk.

Common mistakes:

  • Rewriting the history first and replacing the key later, or never.
  • Keeping an exposed key as a fallback, which leaves it usable by whoever holds it.
  • Treating the incident as one person’s fault rather than a gap in the process.

Follow-up the interviewer might ask:

  • “Which other values would you replace if a whole .env file leaked?”
  • “How would you know whether the old key had been used?”

Next: Chapter 9 builds Otahque’s first page: a URL, the view it leads to, and the first automated test that proves the page works.

PAGE 006