Essential Django Settings Configuration Guide
A Django project involves numerous configuration items. Many settings remain at their default values unless specific adjustments are needed. The settings.py file in a Django project is generated during creation and contains project-specific overrides; it does not display all default values.
Here is a detailed explanation of 61 key Django settings, organized alphabetically. The final section covers settings for caching, authentication, messaging, sessions, and static files.
Settings List: ADMINS, ALLOWED_HOSTS, APPEND_SLASH, DATABASES, DATE_FORMAT, DATE_INPUT_FORMATS, DATETIME_FORMAT, DATETIME_INPUT_FORMATS, DEBUG, DEFAULT_CHARSET, DEFAULT_CONTENT_TYPE, DEFAULT_FROM_EMAIL, DISALLOWED_USER_AGENTS, EMAIL_BACKEND, EMAIL_FILE_PATH, EMAIL_HOST, EMAIL_HOST_PASSWORD, EMAIL_HOST_USER, EMAIL_PORT, EMAIL_SUBJECT_PREFIX, EMAIL_USE_TLS, EMAIL_USE_SSL, EMAIL_SSL_CERTFILE, EMAIL_SSL_KEYFILE, EMAIL_TIMEOUT, FILE_CHARSET, INSTALLED_APPS, LANGUAGE_CODE, LANGUAGES, LOCALE_PATHS, LOGGING, LOGGING_CONFIG, MEDIA_ROOT, MEDIA_URL, MIDDLEWARE, ROOT_URLCONF, SECRET_KEY, TEMPLATES, TIME_ZONE, USE_I18N, USE_L10N, USE_TZ, WSGI_APPLICATION, CACHES, AUTHENTICATION_BACKENDS, AUTH_USER_MODEL, LOGIN_REDIRECT_URL, LOGIN_URL, LOGOUT_REDIRECT_URL, PASSWORD_RESET_TIMEOUT_DAYS, PASSWORD_HASHERS, MESSAGE_LEVEL, MESSAGE_STORAGE, SESSION_COOKIE_AGE, SESSION_COOKIE_NAME, SESSION_ENGINE, SESSION_EXPIRE_AT_BROWSER_CLOSE, SITE_ID, STATIC_ROOT, STATIC_URL, STATICFILES_DIRS.
ADMINS
Default: [] (empty list)
A list of individuals who should receive error notification emails when DEBUG is False. Each entry should be a tuple of (full name, email address).
ADMINS = [('Alice Johnson', 'alice@example.net'), ('Bob Smith', 'bob@example.org')]
ALLOWED_HOSTS
Default: [] (empty list)
Defines the host/domain names that this Django instance can serve. This is a security measure to prevent HTTP Host header attacks. Values can be domain names, IP addresses, or wildcards.
ALLOWED_HOSTS = ['localhost', 'api.example.com', '.subdomain.net', '192.168.1.10']
When DEBUG=True and ALLOWED_HOSTS is empty, it defaults to ['localhost', '127.0.0.1', '[::1]']. Using a wildcard '*' is permissible in development but carries security risks in production.
APPEND_SLASH
Default: True
When True and a requested URL doesn't match any pattern in the URLconf but would match if a trailing slash were appended, Django issues a permanent redirect to the URL with the slash. This requires the CommonMiddleware to be enabled.
DATABASES
Default: {} (empty dictionary)
A nested dictionary containing settings for all databases used by the project. A 'default' database connection must be defined.
SQLite Example:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'project_data.db',
}
}
PostgreSQL Example:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'mydb',
'USER': 'dbuser',
'PASSWORD': 'securepass',
'HOST': 'db.server.local',
'PORT': '5432',
'CONN_MAX_AGE': 600, # Persistent connection for 10 minutes
}
}
Key sub-options include:
ENGINE: The database backend to use (e.g.,'django.db.backends.postgresql').NAME: Database name or SQLite file path.USER,PASSWORD,HOST,PORT: Connection credentials.ATOMIC_REQUESTS: Set toTrueto wrap each request in a database transaction.TEST: A dictionary of settings for test database creation.
DATE_FORMAT & DATETIME_FORMAT
Defaults: 'N j, Y' and 'N j, Y, P'
Specify default display formats for date and datetime fields in templates, respectively (e.g., 'Feb. 4, 2003').
DATE_INPUT_FORMATS & DATETIME_INPUT_FORMATS
Defaults: Lists of valid input string formats for forms. These settings define which string formats are accepted when parsing dates and times from form input.
DEBUG
Default: False
The most critical security and development setting. When True, detailed error pages are shown. When False, error details are hidden, and ALLOWED_HOSTS must be properly configured. Must be set to False in production.
DEFAULT_CHARSET & DEFAULT_CONTENT_TYPE
Defaults: 'utf-8' and 'text/html'
The default character set and MIME type for HttpResponse objects.
DEFAULT_FROM_EMAIL
Default: 'webmaster@localhost'
Default email address used as the sender for automated emails sent by Django.
DISALLOWED_USER_AGENTS
Default: [] (empty list)
A list of compiled regex objects that match User-Agent strings to be blocked. Requires CommonMiddleware.
EMAIL CONFIGURATION (Backend, Host, Port, Security)
A suite of settings for configuring email delivery.
EMAIL_BACKEND: The class used to send emails (default: SMTP).EMAIL_HOST,EMAIL_PORT,EMAIL_HOST_USER,EMAIL_HOST_PASSWORD: SMTP server credentials.EMAIL_USE_TLS/EMAIL_USE_SSL: Security protocols. These are mutually exclusive.EMAIL_SUBJECT_PREFIX: String prepended to subject lines of admin emails.
FILE_CHARSET
Default: 'utf-8'
The character encoding used when Django reads template files and initial SQL data files from disk.
INSTALLED_APPS
Default: [] (empty list)
A critical setting listing all Django applications enabled in this project. Includes Django's contrib apps and your project's apps.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.core',
'myapp.api',
]
INTERNATIONALIZATION (i18n) SETTINGS
LANGUAGE_CODE: The default language code for the project (e.g.,'en-us'or'zh-hans'). RequiresUSE_I18N = True.LANGUAGES: A list of all available languages as (code, name) tuples.USE_I18N: Boolean to enable Django's translation system.USE_L10N: Boolean to enable localization of data formats (numbers, dates).LOCALE_PATHS: List of directories where Django looks for translation message files.
LOGGING & LOGGING_CONFIG
Settings for Python's logging framework integration. LOGGING is a dictionary of logging configuration.
MEDIA_ROOT & MEDIA_URL
MEDIA_ROOT: Absolute filesystem patth to the directory for user-uploaded files.MEDIA_URL: URL that handles media served fromMEDIA_ROOT(must end with/). Important: These must be different fromSTATIC_ROOTandSTATIC_URL.
MIDDLEWARE
Default: None
A list of middleware classes to use. New projects are populated with Django's default middleware stack.
ROOT_URLCONF
Default: Not specified
A string representing the full Python import path to the root URL configuration module (e.g., 'myproject.urls').
SECRET_KEY
Default: '' (empty string)
A secret key used for cryptographic signing. This must be set to a unique, unpredictable value and kept secret. Django will not start without it. Its automatically generated when a project is created.
TEMPLATES
Default: [] (empty list)
A list of dictionaries configuring template engines.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
Key sub-options:
BACKEND: The template engine class.DIRS: List of directories to search for templates.APP_DIRS: Whether to look for templates in each app'stemplatesdirectory.
TIME_ZONE, USE_TZ
TIME_ZONE: A string representing the time zone (e.g.,'Asia/Shanghai'for China).USE_TZ: Boolean indicating whether to use timezone-aware datetimes. WhenFalse, Django uses naive datetimes in theTIME_ZONE. For simplicity with a fixed local time, setUSE_TZ = False.
WSGI_APPLICATION
Default: None
The full Python path to the WSGI application object that Django's built-in servers use.
CACHES
Default: {'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}
A dictionary configuring cache systems. A 'default' cache is required.
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.redis.RedisCache',
'LOCATION': 'redis://127.0.0.1:6379/1',
'TIMEOUT': 3600,
}
}
Key sub-options: BACKEND, LOCATION, TIMEOUT (seconds), OPTIONS.
AUTHENTICATION SETTINGS
AUTHENTICATION_BACKENDS: List of authentication backends.AUTH_USER_MODEL: String defining the custom user model (e.g.,'accounts.CustomUser').LOGIN_URL,LOGIN_REDIRECT_URL,LOGOUT_REDIRECT_URL: URL paths for auth views.PASSWORD_HASHERS: List of hashing algorithms used for password storage.PASSWORD_RESET_TIMEOUT_DAYS: Validity period for a password reset link.
MESSAGE FRAMEWORK SETTINGS
MESSAGE_LEVEL: Minimum message level to record.MESSAGE_STORAGE: Backend class for storing messages (e.g., session, cookie).
SESSION SETTINGS
SESSION_COOKIE_AGE: Lifetime of the session cookie in seconds.SESSION_COOKIE_NAME: Name of the cookie to use for sessions.SESSION_ENGINE: Where to store session data (database, cache, file, signed cookies).SESSION_EXPIRE_AT_BROWSER_CLOSE: Whether sessions expire on browser close.
SITE_ID
Default: Not specified
The database ID of the current Site object in the django_site table, used for multi-site projects.
STATIC FILES SETTINGS
STATIC_URL: URL prefix for static files (must end with/).STATIC_ROOT: Absolute path to the directory wherecollectstaticwill gather static files for production. Set whenDEBUGisFalse.STATICFILES_DIRS: List of additional directories containing static files to be discovered during development (DEBUG=True) and collected for production.
Example static/media configuration:
import os
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / 'static_assets']
STATIC_ROOT = BASE_DIR / 'staticfiles_collected'
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'user_uploads'