Skip to content
Kuza Ndoto Academy

Settings & Security

IntermediateChapter 6 · Page 21 of 235 min readUpdated 15 Nov 2026

The settings that make development easy are dangerous on a live website. Before going public, you need to switch off debug mode, keep secrets out of your code, restrict which domains your site answers to and turn on HTTPS protections. This page shows how to prepare the Campus Events project safely.

Why development settings are unsafe

startproject creates settings for your own laptop: DEBUG = True, a SECRET_KEY written directly in settings.py and an empty ALLOWED_HOSTS. That's convenient while learning, but on the internet:

  • DEBUG = True shows anyone who triggers an error your source code, file paths, installed apps, many settings and the SQL that ran. It also makes Django keep every query in memory.
  • A leaked SECRET_KEY lets attackers forge signed data such as session cookies and password-reset links.
  • An open host list exposes you to "Host header" attacks.

Read settings from environment variables

An environment variable is a named value set outside your code, by your terminal or hosting provider. Reading secrets from them means the same settings.py can be committed to GitHub safely and used on your laptop and your server.

campus/settings.py

import os
from pathlib import Path

from django.core.exceptions import ImproperlyConfigured

BASE_DIR = Path(__file__).resolve().parent.parent

DEBUG = os.environ.get("DJANGO_DEBUG", "") == "1"

SECRET_KEY = os.environ.get("DJANGO_SECRET_KEY")
if not SECRET_KEY:
    if DEBUG:
        SECRET_KEY = "django-insecure-local-development-only"
    else:
        raise ImproperlyConfigured("Set the DJANGO_SECRET_KEY environment variable.")

ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS", "127.0.0.1,localhost").split(",")

How this behaves:

  • Safe default: DEBUG is False unless you deliberately set DJANGO_DEBUG=1. Forgetting a variable makes the site more secure, not less.
  • Fails loudly: in production, a missing secret key stops the site from starting with a clear message instead of silently using a weak key.
  • Flexible hosts: DJANGO_ALLOWED_HOSTS takes a comma-separated list such as campus-events.example.com,www.campus-events.example.com.

To work locally with debug mode on, set the variable in your terminal before running the server:

# Windows PowerShell
$env:DJANGO_DEBUG = "1"

# Windows Command Prompt
set DJANGO_DEBUG=1

# macOS / Linux
export DJANGO_DEBUG=1

python manage.py runserver

Variables set this way last until you close the terminal. Many developers keep them in a .env file loaded by the python-dotenv package; if you do, add .env to .gitignore.

Generating a strong SECRET_KEY

Never reuse the development key in production. Django can generate a new random one:

python -c "from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())"
k9#v2m!x7@q$z1r^w8e&t4y_u6i0o-p3a5s(d)f+g=h%j*l

Your key will be different every time; that's the point. Paste it into your host's environment variable settings, not into your code. If a key is ever committed to a public repository, generate a new one: changing it logs everyone out, but that's far better than leaving it exposed.

ALLOWED_HOSTS

When DEBUG is False, Django only answers requests whose Host header matches ALLOWED_HOSTS. Others get 400 Bad Request. If the list is empty, runserver refuses to start:

CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False.

A leading dot matches a domain and all its subdomains: ".example.com" covers example.com and www.example.com. Avoid "*", which allows any host and defeats the purpose.

Every live site should use HTTPS. Most hosts provide a free certificate. Once your site is on HTTPS, add these settings, ideally only when DEBUG is off:

campus/settings.py

if not DEBUG:
    SECURE_SSL_REDIRECT = True          # send http:// visitors to https://
    SESSION_COOKIE_SECURE = True        # only send the login cookie over HTTPS
    CSRF_COOKIE_SECURE = True           # only send the CSRF cookie over HTTPS
    SECURE_HSTS_SECONDS = 3600          # tell browsers "HTTPS only" for one hour; raise later
    SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
  • SECURE_PROXY_SSL_HEADER is needed when your app runs behind a proxy that handles HTTPS for you, which is the case on most platforms such as Render. Only set it if your host's documentation says the proxy sends this header; otherwise SECURE_SSL_REDIRECT can cause an endless redirect loop.
  • HSTS makes browsers refuse plain HTTP for your domain. Start with a small value and increase it (for example to 31536000, one year) once everything works.
  • If forms fail after deploying with "CSRF verification failed ... Origin checking failed", add your full address to CSRF_TRUSTED_ORIGINS, e.g. ["https://campus-events.example.com"].

Let Django check your settings

Django has a built-in deployment checklist. Run it with your production environment variables set:

python manage.py check --deploy

Before adding the HTTPS settings above, you'd see warnings like these (messages shortened):

System check identified some issues: WARNINGS: ?: (security.W004) You have not set a value for the SECURE_HSTS_SECONDS setting. ... ?: (security.W008) Your SECURE_SSL_REDIRECT setting is not set to True. ... ?: (security.W012) SESSION_COOKIE_SECURE is not set to True. ... ?: (security.W016) You have 'django.middleware.csrf.CsrfViewMiddleware' in your MIDDLEWARE, but you have not set CSRF_COOKIE_SECURE to True. ... System check identified 4 issues (0 silenced).

Work through each warning until the list is empty or you understand why one doesn't apply. Read the official deployment checklist in the Django docs as well.

Other production essentials

  • Database passwords belong in environment variables too, never in code.
  • Custom error pages: with DEBUG = False, Django uses templates/404.html and templates/500.html if they exist. Make them friendly and on-brand.
  • Keep Django updated: install new 5.2.x releases promptly, since they contain security fixes.
Common mistake

Pushing a project to a public GitHub repository with the original SECRET_KEY and DEBUG = True still in settings.py, then deploying it unchanged. Automated bots scan GitHub for leaked secrets within minutes. Move secrets to environment variables before your first push.

Key points

  • Never run a live site with DEBUG = True.
  • Read SECRET_KEY, DEBUG, ALLOWED_HOSTS and database credentials from environment variables, with safe defaults.
  • Set ALLOWED_HOSTS to your real domain names.
  • Turn on HTTPS settings such as SECURE_SSL_REDIRECT and secure cookies.
  • Run python manage.py check --deploy before every launch.
Up next · Going LiveDeploying DjangoPut your site on the internet.
→

Tip: use the ← and → keys to move between pages.