<Sagar/>

How to Manage Django Settings for Local and Production Environments

124

How to Manage Django Settings for Local and Production Environments

Introduction

When developing a Django project, it’s crucial to maintain separate settings for local development and production environments. This prevents issues such as exposing sensitive credentials, using the wrong database, or running with debug mode enabled in production.

In this blog, we’ll structure Django settings efficiently using a modular approach. We’ll create a settings/ folder with separate files for base settings, local settings, and production settings.


Why Use Multiple Settings Files?

A single settings.py file often leads to:

  • Hardcoded sensitive credentials (e.g., API keys, database passwords).

  • Difficulty managing environment-specific configurations.

  • Risk of deploying with insecure settings (e.g., DEBUG=True).

A structured approach makes it easier to manage configurations across different environments.


Step 1: Create a settings Folder

Inside your Django project, create a settings/ directory and move settings.py inside it. Then, create three files:

  • base_settings.py → Contains common settings.

  • local_settings.py → Local development settings.

  • prod_settings.py → Production-specific settings.

  • __init__.py → Loads the correct settings based on the environment.

Your project structure should look like this:

project_root/
│── manage.py
│── your_app_name/
│   │── __init__.py
│   │── settings/
│   │   │── __init__.py
│   │   │── base_settings.py
│   │   │── local_settings.py
│   │   │── prod_settings.py
│   │── wsgi.py
│── .env

Step 2: Create __init__.py for Dynamic Settings Loading

The __init__.py file inside the settings folder determines whether to load local or production settings based on an environment variable.

from .base_settings import *
import os
if os.environ.get("mod") == "production":
    from .prod_settings import *
else:
    from .local_settings import *

This script:

  • Loads base settings first.

  • Checks the environment variable mod.

  • Loads prod_settings.py if mod=production, otherwise loads local_settings.py.

To set this environment variable, use:

  • Linux/macOS: export mod=production

  • Windows (CMD): set mod=production


Step 3: Configure base_settings.py

This file contains common settings shared across all environments:

from pathlib import Path
from dotenv import load_dotenv
import os
# Load environment variables
load_dotenv()
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = os.environ.get("SECRET_KEY", "your-default-secret-key")
DEBUG = True
ALLOWED_HOSTS = []
# Installed apps
INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "rest_framework",
    "oauth2_provider",
    "social_django",
    "drf_social_oauth2",
    "corsheaders",
]
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 = "your_app_name.urls"
TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [],
        "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 = "your_app_name.wsgi.application"
# Default database
DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": BASE_DIR / "db.sqlite3",
    }
}
LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_TZ = True
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

Step 4: Configure prod_settings.py

DEBUG = False
ALLOWED_HOSTS = ["yourdomain.com"]
STATIC_URL = "static/"

Key Changes for Production:

  • DEBUG = False for security.

  • ALLOWED_HOSTS should include the production domain.


Step 5: Configure local_settings.py

DEBUG = True
ALLOWED_HOSTS = ["*"]
STATIC_URL = "static/"
CORS_ORIGIN_ALLOW_ALL = True

Key Changes for Local:

  • DEBUG = True for easier debugging.

  • ALLOWED_HOSTS = ["*"] allows all hosts (use cautiously).

  • CORS_ORIGIN_ALLOW_ALL = True to enable API requests from any origin (use only in local development).


Step 6: Use Environment Variables for Secrets

Create a .env file at the root of your project to store sensitive data securely:

SECRET_KEY=your-secret-key-here
mod=local

Then, use load_dotenv() in base_settings.py to load these values.


Step 7: Running Django with the Correct Settings

Use the following command to switch environments:

# For local development
export mod=local
# For production
export mod=production

On Windows (CMD):

set mod=local

Now, Django will automatically load the correct settings based on the environment.


Conclusion

Using this structured approach, you can efficiently manage Django settings for local and production environments without risking security issues or deployment problems. 🚀

With separate settings files, environment variables, and a dynamic loader, you ensure your project runs smoothly across different environments. 🎯


Next Steps

  • Implement database-specific settings in prod_settings.py.

  • Use django-environ for managing environment variables.

  • Automate environment switching with Docker or Gunicorn.

Have questions? Drop a comment below! 💬

Backend
Django
Performance Optimization
Accessibility
Arnold Gunter

Written by Sagar Sangwan

👨‍💻 Programmer | ✈️ Love Traveling | 🍳 Enjoy Cooking | Building cool tech and exploring the world!

View more blogs by me CLICK HERE

Loading related blogs...

Newsletter subscription

SUBSCRIBE to Newsletter

In this newsletter we provide latest news about technology, business and startup ideas. Hope you like it.