Django Settings (settings.py)
The settings.py file is the core configuration module for a Django project. It defines everything from database connections to installed apps and localization settings.
Below is an explanation of the default settings generated by django-admin startproject, including common values and best practices.
Core Settings
BASE_DIR
The absolute path to the directory containing manage.py. By default, it's defined using the pathlib module.
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parentSECRET_KEY
A cryptographic key used to provide cryptographic signing (e.g., sessions, password reset tokens, CSRF tokens).
- Security: Never hardcode this in production or commit it to version control. Always load it from environment variables.
import os
SECRET_KEY = os.environ.get("DJANGO_SECRET_KEY", "insecure-default-key")DEBUG
A boolean that turns on/off debug mode.
- Values:
True(development) orFalse(production). - Security: NEVER run with
DEBUG = Truein production. It leaks sensitive configuration and source code through detailed error pages.
ALLOWED_HOSTS
A list of strings representing the host/domain names that this Django site can serve. This is a security measure to prevent HTTP Host header attacks.
- Values: Required when
DEBUG = False. - Examples:
['example.com', 'www.example.com']. Use['.example.com']to allow a domain and all its subdomains. In development withDEBUG = True,['localhost', '127.0.0.1', '[::1]']are implicitly allowed.
Application Definition
INSTALLED_APPS
A list of strings designating all applications that are enabled in this Django installation.
INSTALLED_APPS = [
"django.contrib.admin", # Admin interface
"django.contrib.auth", # Authentication system
"django.contrib.contenttypes",# Framework for content types (Generic relations)
"django.contrib.sessions", # Session framework
"django.contrib.messages", # Messaging framework
"django.contrib.staticfiles", # Static files management
]TIP
If you are building a pure API (e.g., with Django REST Framework) without server-side HTML rendering, you can often remove django.contrib.admin, django.contrib.messages, and django.contrib.staticfiles to optimize performance.
MIDDLEWARE
A list of middleware components to hook into Django's request/response processing. Order is critical.
- Default Stack: Includes Security, Sessions, Common (URL rewriting), CSRF protection, Authentication, Messages, and Clickjacking protection.
ROOT_URLCONF
A string representing the full Python import path to your root URLconf (usually <project_name>.urls).
TEMPLATES
A list containing settings for all template engines to be used.
BACKEND: Usually"django.template.backends.django.DjangoTemplates".DIRS: List of directories where the engine should look for template source files (e.g.,[BASE_DIR / "templates"]).APP_DIRS: Whether the engine should look for templates inside installed applications (Trueby default).
WSGI_APPLICATION & ASGI_APPLICATION
The full Python path to the WSGI (synchronous) or ASGI (asynchronous) application object that Django's built-in servers (and production servers) will use.
Database Configuration
DATABASES
A dictionary containing the settings for all databases to be used. The default database is required.
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
}DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": "mydatabase",
"USER": "mydatabaseuser",
"PASSWORD": "mypassword",
"HOST": "127.0.0.1",
"PORT": "5432",
}
}Password Validation
AUTH_PASSWORD_VALIDATORS
A list of validators that are used to check the strength of user passwords.
UserAttributeSimilarityValidator: Rejects passwords similar to username/email.MinimumLengthValidator: Requires a minimum length (default 8).CommonPasswordValidator: Rejects passwords found in a common password list.NumericPasswordValidator: Rejects passwords containing only numbers.
Internationalization (i18n) & Localization (l10n)
These settings control the language and timezone formatting of your application.
LANGUAGE_CODE
A string representing the default language code for this installation.
- Format:
language-region(e.g.,'en-us','es-ar','fr'). - Options: Any standard IETF language tag.
TIME_ZONE
A string representing the local time zone for this installation.
- Default:
'UTC' - Values: Any valid IANA Time Zone database string. Common values include:
'America/New_York''Europe/London''Asia/Kolkata''Australia/Sydney'
TIP
In Python 3.9+, you can view all valid time zones programmatically using the standard library: import zoneinfo; print(zoneinfo.available_timezones())
USE_I18N
A boolean that specifies whether Django's translation system should be enabled.
- Performance: Set to
Falseif you don't need translations, as it provides a minor performance boost.
USE_TZ
A boolean that specifies if datetimes will be timezone-aware by default.
- Default:
True. When true, Django strictly stores date/time in UTC internally in the database, and converts it to the user's/default timezone (TIME_ZONEsetting) on forms and templates.
If you set this to False, Django stops converting everything to UTC. Instead, it stores dates and times in the database exactly as the local time defined in your TIME_ZONE. However, doing this is strongly discouraged because it makes handling daylight saving time and global users very difficult.
Static and Media Files
STATIC_URL
The URL to use when referring to static files (CSS, JavaScript, Images).
- Default:
"static/"
DEFAULT_AUTO_FIELD
The default primary key field type to use for models that don't have a field with primary_key=True.
- Default:
"django.db.models.BigAutoField"(A 64-bit integer, guaranteeing you won't run out of IDs).
