Django settings.py

Prerequisites

Quick intro

  • The settings.py file is the heart of your Django project’s configuration.
  • It contains all the settings and configurations for your project.
  • Let’s dive into some of the key sections and settings within this file.
  • settings.py file can be find at my_project/settings.py
.
├── db.sqlite3
├── manage.py
└── my_project
    ├── __init__.py
    ├── asgi.py
    ├── settings.py
    ├── urls.py
    └── wsgi.py

Basic Settings

DEBUG

  • DEBUG = True - in development environment to find and fix the issues.
  • DEBUG = False - in production environment for security reasons.
DEBUG = True

ALLOWED_HOSTS

  • Defines a list of strings representing the host/domain names that this Django site can serve.
  • Add your domain names here in production.
ALLOWED_HOSTS = ["localhost", "mywebsite.com"]

BASE_DIR

  • It's the root directory of django project
from pathlib import Path

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

Database Configuration

  • Django uses a database to store application data.
  • The default configuration uses SQLite
  • For production, you might use PostgreSQL, MySQL, or another database

SQLite Config

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

PostgreSQL Config

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'mydatabase',
        'USER': 'mydatabaseuser',
        'PASSWORD': 'mypassword',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}

MySQL Config

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mydatabase',
        'USER': 'mydatabaseuser',
        'PASSWORD': 'mypassword',
        'HOST': 'localhost',
        'PORT': '3306',
    }
}

Installed apps

  • This setting defines the list of applications that are enabled in our Django project
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # our apps
    'my_app',
]

Middlewares

  • Middleware is a framework of hooks into Django’s request/response processing.
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',
]

Templates

  • Django uses a templating system to manage your HTML templates
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',
            ],
        },
    },
]

Static Files

  • Django can manage static files (CSS, JavaScript, images)
STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / "static"]

Media Files

  • If your application handles file uploads, you'll need to configure media files
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / "media"

Security Settings

SECRET_KEY

  • A large random value used for cryptographic signing. Keep this value secret.
SECRET_KEY = 'your-secret-key'

SECURE_BROWSER_XSS_FILTER

  • Enables the browser's XSS filtering and helps prevent XSS attacks.
SECURE_BROWSER_XSS_FILTER = True
  • Ensures the CSRF cookie is only sent over HTTPS.
CSRF_COOKIE_SECURE = True
  • Ensures the session cookie is only sent over HTTPS.
SESSION_COOKIE_SECURE = True

Internationalization

  • Django supports full internationalization and localization:
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True

Logging

  • Django provides a flexible logging system
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': BASE_DIR / 'debug.log',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}

Authentication Settings

  • Django uses authentication backends to authenticate users.
  • By default, Django uses the ModelBackend, which authenticates against the username and password fields of django.contrib.auth.models.User.

AUTHENTICATION_BACKENDS

AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
]

AUTH_USER_MODEL

  • Django uses this user modal for authentication purposes.
AUTH_USER_MODEL = 'auth.User'

Login/Logout settings

  • Django provides settings to manage user registration and login

LOGIN_URL

  • The URL where requests are redirected for login.
LOGIN_URL = '/login/'

LOGIN_REDIRECT_URL

  • The URL where requests are redirected after a successful login.
LOGIN_REDIRECT_URL = '/profile/'

LOGOUT_REDIRECT_URL

  • The URL where requests are redirected after a successful logout.
LOGOUT_REDIRECT_URL = '/'

Middleware

  • Django requires authentication middleware to manage user sessions and authentication.
  • Ensure the following middleware is included in your MIDDLEWARE setting
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',
]

Email Backend

  • For user authentication processes like password reset, Django uses an email backend.
  • You can configure it as follows:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.example.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'your-email-password'
DEFAULT_FROM_EMAIL = '[email protected]'

References: