Django Production Settings
Introduction
When deploying a Django application to production, you need to ensure that your settings are properly configured for security, performance, and reliability. The default settings provided by Django's startproject
command are designed for development, not production use. This guide will walk you through the essential configuration changes needed to make your Django application production-ready.
Why Production Settings Matter
Development settings prioritize convenience and debugging capabilities, while production settings focus on:
- Security: Protecting your application from attacks and data breaches
- Performance: Optimizing resource usage and response times
- Reliability: Ensuring stable operation under load
- Scalability: Allowing your application to grow with increasing demand
Failing to configure production settings correctly can result in security vulnerabilities, slow performance, and potential data loss.
Setting Up a Production Configuration
Separating Development and Production Settings
A common practice is to have separate settings files for different environments. Let's explore how to structure this:
# Project structure
myproject/
├── myproject/
│ ├── __init__.py
│ ├── settings/
│ │ ├── __init__.py
│ │ ├── base.py
│ │ ├── development.py
│ │ └── production.py
│ ├── urls.py
│ └── wsgi.py
└── manage.py
Base Settings (base.py
)
# Common settings for all environments
import os
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent.parent
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 = [
# Template configuration
]
WSGI_APPLICATION = 'myproject.wsgi.application'
# Internationalization settings
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files
STATIC_URL = '/static/'
Development Settings (development.py
)
from .base import *
DEBUG = True
SECRET_KEY = 'your-development-secret-key'
ALLOWED_HOSTS = ['localhost', '127.0.0.1']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Development-specific settings
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'