Skip to the workspace
Pebellslearn by building
Projects and Apps  ›  Lesson

settings.py — One Place for Configuration

settings.py 14 minsettings.py is a plain Python module of upper-case names that configure the whole project, from installed apps and the database to debug mode and allowed hosts.

django / settings.py — One Place for Configuration

Explore each scene at your own pace.

01 · The rule

The rule

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 images

Four of these usually change between your laptop and a public server:

  • DEBUG = True shows a detailed page on errors, including code and settings. Wonderful locally, dangerous in public. In production it must be False.
  • SECRET_KEY signs 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_HOSTS lists the domain names the site will serve. With DEBUG = True and an empty list, Django allows localhost and 127.0.0.1. With DEBUG = False and an empty list, every request gets 400 Bad Request.
  • DATABASES starts 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:
    ...
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.