backend / web frameworks / django / 10_settings_py.md

settings.py in Django: A Comprehensive Guide

3 interview angles 4 min read source

settings.py in Django: A Comprehensive Guide

Introduction

The settings.py file is the central configuration file for a Django project. It contains all the settings and configuration options that control the behavior of your Django application, including database connections, installed apps, middleware, static files, security, and more.

Purpose of settings.py

  • Centralizes all project configuration
  • Controls environment-specific settings (development, production, testing)
  • Manages security, database, and application behavior
  • Enables easy customization and scaling

Structure of settings.py

A typical settings.py file includes the following sections:

  1. Basic Project Settings

    • BASE_DIR: The base directory of the project
    • SECRET_KEY: Secret key for cryptographic signing
    • DEBUG: Debug mode (True/False)
    • ALLOWED_HOSTS: List of allowed host/domain names
  2. Application Definition

    • INSTALLED_APPS: List of Django and third-party apps
    • MIDDLEWARE: List of middleware classes
    • ROOT_URLCONF: Root URL configuration module
    • TEMPLATES: Template engine configuration
    • WSGI_APPLICATION: WSGI application entry point
  3. Database Configuration

    • DATABASES: Database engine, name, user, password, host, port
  4. Password Validation

    • AUTH_PASSWORD_VALIDATORS: Password validation rules
  5. Internationalization

    • LANGUAGE_CODE, TIME_ZONE, USE_I18N, USE_L10N, USE_TZ
  6. Static and Media Files

    • STATIC_URL, STATIC_ROOT, MEDIA_URL, MEDIA_ROOT
  7. Security Settings

    • CSRF_COOKIE_SECURE, SESSION_COOKIE_SECURE, SECURE_SSL_REDIRECT, etc.
  8. Custom/Third-Party Settings

    • API keys, email backend, logging, etc.

Example settings.py (Simplified)

import os
from pathlib import Path

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

SECRET_KEY = 'your-secret-key'
DEBUG = True
ALLOWED_HOSTS = ['localhost', '127.0.0.1']

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Your apps here
]

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 = 'myproject.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],
        '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',
            ],
        },
    },
]

WSGI_APPLICATION = 'myproject.wsgi.application'

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

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_L10N = True
USE_TZ = True

STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_ROOT = BASE_DIR / 'staticfiles'
MEDIA_ROOT = BASE_DIR / 'mediafiles'

Common settings.py Options

  • DEBUG: Should be False in production
  • ALLOWED_HOSTS: Always set this for security
  • SECRET_KEY: Keep this secret and never commit to version control
  • DATABASES: Use environment variables for credentials
  • STATIC/MEDIA: Configure for deployment (e.g., AWS S3, CDN)
  • EMAIL_BACKEND: Configure for sending emails
  • LOGGING: Set up logging for error tracking
  • THIRD-PARTY SETTINGS: API keys, authentication backends, etc.

Best Practices

  1. Environment Separation

    • Use different settings for development, testing, and production (e.g., settings/dev.py, settings/prod.py)
    • Use environment variables for sensitive data (with os.environ or python-dotenv)
  2. Security

    • Never commit SECRET_KEY or credentials to version control
    • Set DEBUG = False in production
    • Use secure cookies and HTTPS settings
  3. Scalability

    • Use environment-specific settings for databases, caches, and static files
    • Modularize settings for large projects
  4. Maintainability

    • Document custom settings
    • Group related settings together
    • Use comments to explain non-obvious configurations

Interview Questions and Answers

Q1: What is the purpose of the settings.py file in Django?

  • It centralizes all configuration for a Django project, including database, security, installed apps, middleware, and more.

Q2: How do you manage different settings for development and production?

  • Use multiple settings files (e.g., dev.py, prod.py) and environment variables to control which settings are loaded.

Q3: Why should DEBUG be set to False in production?

  • When DEBUG is True, Django displays detailed error pages and stack traces, which can expose sensitive information. Always set DEBUG = False in production.

Q4: How do you keep sensitive information out of version control?

  • Use environment variables and never commit secrets or credentials to your repository.

Q5: What are some common mistakes with settings.py?

  • Leaving DEBUG = True in production
  • Not setting ALLOWED_HOSTS
  • Committing SECRET_KEY to version control
  • Hardcoding database credentials

Summary

  • settings.py is the heart of Django project configuration.
  • Use environment variables and separate files for different environments.
  • Always secure sensitive data and follow best practices for maintainability and scalability.
  • Understanding and managing settings.py is crucial for any Django developer.

Interview angle

  • “How do you manage settings across environments?” - one base module with per-environment overrides, values from the environment, and validation at startup. Never commit secrets; never branch on DEBUG for behaviour that matters.
  • “What must never be wrong in production?” - DEBUG = False (it leaks stack traces and settings), a correct ALLOWED_HOSTS, a real SECRET_KEY from the environment, and secure cookie and HSTS settings.
  • “Why validate settings at startup?” - a missing variable should crash on boot where deployment tooling sees it, rather than at the first request that touches that code path.