settings.py — One Place for Configuration
Which database does the cookbook use? Which apps are switched on? Should errors show a detailed debug page or a plain one? Django answers every question like these by looking in one file. When the project misbehaves in a way that is not about your code, settings.py is the first place to look.
The rule
Settings are UPPER-CASE names in one Python file; Django reads them at start-up.
settings.py is ordinary Python. Django reads the names written in capitals and ignores the rest. The ones you will touch first:
BASE_DIR = Path(__file__).resolve().parent.parent # the project folder
SECRET_KEY = "django-insecure-..." # signs cookies and tokens
DEBUG = True # detailed error pages
ALLOWED_HOSTS = [] # host names this site answers to
INSTALLED_APPS = [..., "recipes"] # apps that are switched on
MIDDLEWARE = [...] # layers every request passes through
ROOT_URLCONF = "cookbook.urls" # where URL matching starts
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
}
TIME_ZONE = "UTC"
USE_TZ = True # store times with a time zone
STATIC_URL = "static/" # URL prefix for CSS, JS and imagesFour of these usually change between your laptop and a public server:
DEBUG = Trueshows a detailed page on errors, including code and settings. Wonderful locally, dangerous in public. In production it must beFalse.SECRET_KEYsigns session cookies and password-reset links. Anyone who has it can forge them. In production, read it from an environment variable and never commit it.ALLOWED_HOSTSlists the domain names the site will serve. WithDEBUG = Trueand an empty list, Django allowslocalhostand127.0.0.1. WithDEBUG = Falseand an empty list, every request gets 400 Bad Request.DATABASESstarts as SQLite, a single file that needs no server. Real deployments usually switch to PostgreSQL here.
In your own code, read settings through django.conf.settings, never by importing the file directly:
from django.conf import settings
if settings.DEBUG:
...The shortcut
When something is wrong across the whole site, not one page, suspect a setting. Ask "which setting owns this?" and jump straight to it.
The symptom
Every page on
cookbook.example.comreturns 400 Bad Request.
The trap is shipping development values: DEBUG = True and the generated SECRET_KEY both sitting in a public repository.
Drills
Answer fast — trust the rule.
Which setting tells Django where URL matching starts?
With DEBUG = False and ALLOWED_HOSTS = [], what does every request get?
What database does a new project use until you change DATABASES?
How should your own code read the DEBUG setting?
Remember
- Settings are upper-case names in one Python file, read at start-up.
- Whole-site problem? Ask "which setting owns this?"
- Trap:
DEBUG = Trueor a committedSECRET_KEYon a public server.
