Production Settings

Harden settings.py before going live.

Development defaults are unsafe for production. Before deploying, adjust the key settings that affect security and behavior.

  • Set DEBUG = False — never leak tracebacks publicly.
  • Fill ALLOWED_HOSTS with your real domains.
  • Load SECRET_KEY and database credentials from the environment.
  • Switch to a production database such as PostgreSQL.

Example

Example · python
import os

DEBUG = False
ALLOWED_HOSTS = ["example.com", "www.example.com"]
SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql",
        "NAME": os.environ["DB_NAME"],
        "USER": os.environ["DB_USER"],
        "PASSWORD": os.environ["DB_PASSWORD"],
        "HOST": os.environ.get("DB_HOST", "localhost"),
    }
}

When to use it

  • A developer sets DEBUG=False and defines ALLOWED_HOSTS before pushing the Django app to a production server.
  • A team separates development and production settings into different files loaded via the DJANGO_SETTINGS_MODULE env var.
  • A developer sets CONN_MAX_AGE in the production DATABASES dict to reuse database connections between requests.

More examples

Minimal production settings

Shows the minimum settings to change when going to production: debug off, hosts, secret key, persistent DB connections.

Example · python
# settings/production.py
from .base import *

DEBUG = False
ALLOWED_HOSTS = ["mysite.com", "www.mysite.com"]
SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]

DATABASES["default"]["CONN_MAX_AGE"] = 60

Persistent database connections

Reads database credentials from environment variables and enables 60-second connection reuse.

Example · python
DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql",
        "NAME": os.environ["DB_NAME"],
        "USER": os.environ["DB_USER"],
        "PASSWORD": os.environ["DB_PASSWORD"],
        "HOST": os.environ["DB_HOST"],
        "CONN_MAX_AGE": 60,
    }
}

Production email backend

Configures the SMTP email backend with SendGrid credentials stored in environment variables.

Example · python
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "smtp.sendgrid.net"
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = "apikey"
EMAIL_HOST_PASSWORD = os.environ["SENDGRID_API_KEY"]

Discussion

  • Be the first to comment on this lesson.