Django Settings Best Practice: Split Settings by Environment

 Python Django Split Settings (Best Practice Structure) In production-ready Django projects, using a single settings.py quickly becomes messy and risky. A better approach is splitting settings by environment: settings/ base.py development.py production.py 🧱 1. BASE.PY (Shared Configuration) 👉 This is the core of the project (used everywhere) ✅ Keep here: INSTALLED_APPS MIDDLEWARE (common only) ROOT_URLCONF TEMPLATES WSGI / ASGI AUTH_USER_MODEL LANGUAGE / TIME_ZONE STATIC_URL, MEDIA_URL Third-party apps ❌ DO NOT include here: DEBUG DATABASES ALLOWED_HOSTS Security settings (SSL, HSTS) Environment-specific configs 👉 Rule: Only shared configuration 🧪 2. DEVELOPMENT.PY (Local Environment) 👉 Optimized for speed and debugging ✅ Add here: from .base import * DEBUG = True ALLOWED_HOSTS = [] Database: DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": BASE_DIR / "db.sqlite3", } } Dev-friendly settings: SECURE_SSL_REDIRECT = False SESSION_COOKIE_SECURE = False CSRF_COOKIE_SECURE = False EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend" ❌ Avoid: PostgreSQL config SSL/HSTS production email servers 🚀 3. PRODUCTION.PY (Live Server) 👉 Secure, optimized, real deployment settings ✅ Add here: from .base import * from decouple import config DEBUG = False Allowed hosts: ALLOWED_HOSTS = ["yourdomain.com", "www.yourdomain.com"] Database (PostgreSQL): DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": config("DB_NAME"), "USER": config("DB_USER"), "PASSWORD": config("DB_PASSWORD"), "HOST": config("DB_HOST"), "PORT": config("DB_PORT"), } } Security (production only): SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_HSTS_SECONDS = 31536000 SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_PRELOAD = True Static files: STATIC_ROOT = BASE_DIR / "staticfiles" ❌ Avoid in production: DEBUG = True SQLite console email backend open ALLOWED_HOSTS insecure cookies 🧠 Key Idea (Simple Rule) FilePurposebase.pyShared foundationdevelopment.pyFast local developmentproduction.pySecure live system ⚡ Why this matters ✔ prevents production mistakes ✔ improves security ✔ separates environments cleanly ✔ easier scaling & deployment ✔ industry standard approach 🚀 Final insight A professional Django project is not defined by features — but by how cleanly it separates environments, security, and configuration logic.

To view or add a comment, sign in

Explore content categories