settings.py#

1. What is settings.py?#

The settings.py file contains all global configuration for a Django project, including installed apps, database settings, middleware, security options, and localization preferences.

settings.py is the central configuration file of a Django project.

Location:

mysite/mysite/settings.py

This file controls how your entire Django project behaves.

If Django is a machine, settings.py is its control panel.


2. What does settings.py control?#

settings.py defines:
  • Installed apps

  • Database configuration

  • Middleware

  • Security options

  • Templates

  • Static & media files

  • Time zone & language

  • Debug mode

Django cannot start without this file.


3. How Django uses settings.py#

When you run:

python manage.py runserver
Django:
  1. Loads mysite.settings

  2. Reads every configuration value

  3. Initializes the project using those values

That’s why manage.py, asgi.py, and wsgi.py all reference:

DJANGO_SETTINGS_MODULE = "mysite.settings"

1️⃣ Project base settings#

from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent
  • BASE_DIR points to the project root

  • Used for paths like database, static files, templates

2️⃣ Security & debug#

SECRET_KEY = 'django-insecure-...'
DEBUG = True
ALLOWED_HOSTS = []
Explanation:
  • SECRET_KEY → cryptographic security key

  • DEBUG=True → show detailed errors (dev only)

  • ALLOWED_HOSTS → domains allowed to access the site

In production:

DEBUG = False

3️⃣ Installed applications#

INSTALLED_APPS = [
    # Django core apps
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # Local apps
    'myapp.apps.MyappConfig',
]
This tells Django:
  • Which apps are enabled

  • Which features are active

Your app must be listed here to work.

4️⃣ Middleware#

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
Middleware:
  • Runs before & after every request

  • Handles security, sessions, authentication, etc.

5️⃣ URL configuration#

ROOT_URLCONF = 'mysite.urls'
This tells Django:

“Use urls.py to route incoming requests.”

6️⃣ Templates#

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
Controls:
  • HTML rendering

  • Template locations

  • Context variables

7️⃣ Database configuration#

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}
Default:
  • SQLite database

  • Stored in db.sqlite3

Later, you can replace this with PostgreSQL or MySQL.

Check out this page for more database configuration.

8️⃣ Password validation#

AUTH_PASSWORD_VALIDATORS = [
    {'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'},
    {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator'},
    {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'},
    {'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'},
]
Used by:
  • Admin panel

  • User authentication

9️⃣ Language & time zone#

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
Controls:
  • Localization

  • Time handling

  • Internationalization

🔟 Static files#

STATIC_URL = 'static/'
Used for:
  • CSS

  • JavaScript

  • Images

In production, static files are served separately.

1️⃣1️⃣ Default primary key type#

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

Defines how primary keys are generated.


4. What NOT to do in settings.py#

  • Put secrets directly (use environment variables)

  • Hardcode production values

  • Delete default sections blindly

  • Mix dev & prod settings in large projects

settings.py

from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = 'django-insecure-f-rfidnmw2piu!q65-ifssb5kks^s-*h#59qxfweni&_oal_yk'

DEBUG = True

ALLOWED_HOSTS = []

INSTALLED_APPS = [
    # Django
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Third-party
    'rest_framework',
    'django_filters',
    # Local
    'myapp.apps.MyappConfig',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'mysite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'mysite.wsgi.application'

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql",
        "NAME": "mysite_db",
        "USER": "mysite_user",
        "PASSWORD": os.environ.get("DB_PASSWORD", ""),
        "HOST": "127.0.0.1",
        "PORT": "5432",

        "CONN_MAX_AGE": 60,
        "CONN_HEALTH_CHECKS": True,

        "OPTIONS": {
            "options": (
                "-c search_path=apps,account,services,orders,public "
                "-c statement_timeout=30000 "
                "-c lock_timeout=5000 "
                "-c idle_in_transaction_session_timeout=60000"
            ),
            # "sslmode": "require",  # enable for cloud
        },
    }
}

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True

STATIC_URL = 'static/'