Master Django Settings Like a Pro with Code Splitting! 🚀

Managing settings in a Django project can get messy easily, especially as your project scales. A single settings.py file often turns into a…

Master Django Settings Like a Pro with Code Splitting! 🚀
Photo by Martijn Baudoin on Unsplash

Managing settings in a Django project can get messy easily, especially as your project scales. A single settings.py file often turns into a bloated, hard-to-maintain mess.

The solution?
Code-splitting Django settings into multiple files based on environments (e.g., development, staging, production). This keeps your configuration more organized, secure, and scalable!

Why we need to Split Django Settings?

To split Django settings into multiple files will better organize by separating settings for development, testing, and production. It improve security by keeping sensitive information out of your version control. Easier debugging by quickly locate and modify environment-specific settings.

Step-by-Step: Splitting Django Settings

By following these steps you can easily split your Django settings with multiple environments.

1. Create a settings/ Directory

Inside your Django project, replace settings.py with a new folder:

mv myproject/settings.py myproject/settings/ 
mkdir myproject/settings 
touch myproject/settings/__init__.py

by following this CLI or you can directly do it in code editor.

2. Create Environment-Specific Settings Files

Inside the settings/ directory, create the following files:

  • base.py → Common settings for all environments.
  • development.py → Settings for local development.
  • production.py → Settings for live deployment.
  • staging.py → Settings for staging (if needed).
touch myproject/settings/base.py 
touch myproject/settings/development.py 
touch myproject/settings/production.py

3. Define Common Settings in base.py

# settings/base.py 
 
from pathlib import Path 
import os 
 
BASE_DIR = Path(__file__).resolve().parent.parent 
 
SECRET_KEY = os.getenv("DJANGO_SECRET_KEY", "your-default-secret-key") 
 
INSTALLED_APPS = [ 
    "django.contrib.admin", 
    "django.contrib.auth", 
    "django.contrib.contenttypes", 
    "django.contrib.sessions", 
    "django.contrib.messages", 
    "django.contrib.staticfiles", 
] 
 
MIDDLEWARE = [ 
    "django.middleware.security.SecurityMiddleware", 
    "django.middleware.common.CommonMiddleware", 
    "django.middleware.csrf.CsrfViewMiddleware", 
    "django.middleware.clickjacking.XFrameOptionsMiddleware", 
] 
 
TEMPLATES = [ 
    { 
        "BACKEND": "django.template.backends.django.DjangoTemplates", 
        "DIRS": [BASE_DIR / "templates"], 
        "APP_DIRS": True, 
        "OPTIONS": {"context_processors": ["django.template.context_processors.request"]}, 
    } 
] 
 
STATIC_URL = "/static/"

4. Define Environment-Specific Settings

development.py – Debug Mode ON

# settings/development.py 
from .base import * # this will import all the common settings 
 
DEBUG = True # Debug mode is True in development 
 
ALLOWED_HOSTS = ["localhost", "127.0.0.1"] 
 
# Sqlite3 database for development 
DATABASES = { 
    "default": { 
        "ENGINE": "django.db.backends.sqlite3", 
        "NAME": BASE_DIR / "db.sqlite3", 
    } 
} 
 
# Email settings for development 
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"

production.py – Debug Mode OFF

# settings/production.py 
from .base import * # this will import all the common settings 
 
DEBUG = False # Debug mode is False in production 
 
ALLOWED_HOSTS = ["yourdomain.com"] 
 
# Postgres database for production 
DATABASES = { 
    "default": { 
        "ENGINE": "django.db.backends.postgresql", 
        "NAME": os.getenv("DB_NAME"), 
        "USER": os.getenv("DB_USER"), 
        "PASSWORD": os.getenv("DB_PASSWORD"), 
        "HOST": os.getenv("DB_HOST"), 
        "PORT": os.getenv("DB_PORT", "5432"), 
    } 
} 
 
# Email settings for production 
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" 
EMAIL_HOST = os.getenv("EMAIL_HOST") 
EMAIL_PORT = os.getenv("EMAIL_PORT") 
EMAIL_USE_TLS = True 
EMAIL_HOST_USER = os.getenv("EMAIL_HOST_USER") 
EMAIL_HOST_PASSWORD = os.getenv("EMAIL_HOST_PASSWORD")

5. Set the Environment Variable for DJANGO_SETTINGS_MODULE

Now, tell Django which settings file to use based on the environment.

For Development:

On the production server, add this in .env file:

DJANGO_SETTINGS_MODULE=myproject.settings.development

For Production:

On the production server add this in .env file:

DJANGO_SETTINGS_MODULE=myproject.settings.production

Or you can set it in wsgi.py or asgi.py:

import os 
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings.production")

Final Thoughts

Splitting your Django settings improves security, maintainability, and scalability. Now, your configurations are cleanly separated, and switching environments is as simple as changing an environment variable.

Have you tried Django settings splitting before? Drop your thoughts below!

Photo by Irina Iriser on Unsplash