Skip to lesson content

PROJECT 8 · LESSON 15 OF 16

Prepare the application for production

Replace local-only assumptions with PostgreSQL, required secrets and collected static assets.

  • environment configuration
  • PostgreSQL
  • WhiteNoise
  • Gunicorn
  • HTTPS

Your workspace: edushop

Continue from lesson 14: Manage fulfillment and verify the complete application. Keep existing files; create or replace the complete files listed below.

Extract the ZIP and open the folder containing manage.py. Create a Python virtual environment, install requirements.txt and run migrate. Read README.md for checkpoint-specific commands and LESSON.md for offline explanations. Checkpoints contain no database records or private credentials.

1. Understand the problem and the concepts

Why we need this feature

A working local server still depends on a local filesystem, debug settings and development defaults. Preparing for production makes those dependencies explicit so the hosted application can fail clearly instead of silently running with unsafe or disposable configuration.

The final application is still the same project. Deployment changes how it is configured and served. It does not require rewriting views into a different frontend.

Django does not automatically read a .env file in this example. Set environment variables in your shell locally or in the hosting dashboard. .env.example is documentation, not an active loader.

Environment variables separate deployment values from source

The same source can run locally or on a host, but database credentials, secret keys and domains differ. os.environ reads the process environment. .env.example documents names and examples; this project does not automatically load a .env file. Set values in the terminal or hosting dashboard. Never commit the real database URL or secret.

For local Unix shells use export NAME=value, and in PowerShell use $env:NAME="value". These affect the current shell and child processes; opening a new terminal may require setting them again. The hosting dashboard stores variables for the deployed service. DEBUG is controlled by DJANGO_DEBUG, and the live service must explicitly set it to 0.

A persistent database is a separate service

Production requires DATABASE_URL and uses PostgreSQL through psycopg. There is no production fallback to SQLite. Ephemeral web-service filesystems can be replaced on deploy, so a local db.sqlite3 is not a durable store. Database migrations create the live schema; they do not import local customers, products or orders.

Use a separate staging database for experiments and concurrency tests. A test runner may need permission to create a test database; do not point destructive tests at customer data. Connection health checks and a bounded connection lifetime help manage reused connections, but they are not a substitute for database monitoring and backups.

Static output and trusted host information

collectstatic copies discovered assets to STATIC_ROOT and builds hashed names through manifest storage. WhiteNoise serves those files without requiring Django template views for each asset. The static source folder remains in the app; collected output is generated during build. Uploaded customer media is a different concern and is not implemented here.

ALLOWED_HOSTS contains hostnames without schemes. CSRF_TRUSTED_ORIGINS contains complete origins such as https://example.onrender.com. These are different lists with different jobs. Secure cookies and SSL redirect belong in production. SECURE_PROXY_SSL_HEADER is enabled only when TRUST_PROXY=1 for the documented trusted hosting proxy; do not trust an arbitrary client-supplied header on an unprotected direct server.

HSTS tells browsers to prefer HTTPS for future visits. This course begins with a short duration and avoids subdomain/preload commitments. Verify HTTPS and your domain configuration before extending such a policy. check --deploy is a useful review aid, not an automatic certification that business operations are ready.

2. Follow the execution flow

Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.

  1. The hosted process reads environment variables before Django settings load.

  2. Production settings require a secret, PostgreSQL URL and valid hosts.

  3. The build installs packages and collects static assets.

  4. The release applies versioned migrations to PostgreSQL.

  5. Gunicorn serves Django behind the trusted HTTPS proxy; WhiteNoise serves collected assets.

Distinguish local and live configuration

  1. Run the local checkpoint with the documented development defaults.
  2. Prepare production variables using a staging PostgreSQL database and DJANGO_DEBUG=0. Run check --deploy and inspect each warning.
  3. Remove DATABASE_URL in that production configuration. Startup should fail clearly instead of creating a fresh SQLite file.

3. Build it, one file at a time

  1. Replace requirements and settings. Install requirements, then run the test suite with the default development SQLite configuration.
  2. Create a separate PostgreSQL learning database and set DATABASE_URL to its connection URL. Run migrate, seed_products and test against that backend before deploying. Use a database role allowed to create a temporary test database, or a separate testing service. Never point tests at production.
  3. Generate a long random DJANGO_SECRET_KEY. With DJANGO_DEBUG=0 set the allowed hostname and HTTPS origin, run collectstatic and check --deploy. The database URL must be present; production settings deliberately refuse SQLite fallback.
  4. Inspect the resulting staticfiles directory. It is generated build output, not a place to edit CSS. Gunicorn serves the application; WhiteNoise serves collected static assets.
Terminal
python -m pip install -r requirements.txt
python manage.py collectstatic --noinput
python manage.py test orders
python -c "import secrets; print(secrets.token_urlsafe(50))"
# Set production variables in your shell or hosting dashboard before these:
python manage.py collectstatic --noinput
python manage.py check --deploy
# Linux / hosting only, after configuration:
# gunicorn config.wsgi:application --bind 0.0.0.0:8000

The paths below are relative to your practice project. Each block is the complete file at this checkpoint. Read its responsibility first, type or copy the code, then use the walkthrough to explain the important statements.

requirements.txt

Pin the verified runtime and deployment packages.

requirements.txt
Django==5.2.18
dj-database-url==3.1.2
whitenoise==6.12.0
gunicorn==23.0.0
psycopg[binary]==3.3.6

Read the code

  1. dj-database-url parses PostgreSQL connection URLs; psycopg is the PostgreSQL driver.
  2. WhiteNoise serves collected application static files. Gunicorn is the Linux production WSGI server; Windows learners run it on hosting rather than native Windows.

config/settings.py

Separate local development defaults from required live configuration.

config/settings.py
from pathlib import Path
import os
import dj_database_url
from django.core.exceptions import ImproperlyConfigured

BASE_DIR = Path(__file__).resolve().parent.parent
DEBUG = os.environ.get("DJANGO_DEBUG", "1") == "1"
SECRET_KEY = os.environ.get("DJANGO_SECRET_KEY", "development-only-key" if DEBUG else "")
if not SECRET_KEY:
    raise ImproperlyConfigured("Set DJANGO_SECRET_KEY when DEBUG is off")
ALLOWED_HOSTS = [host.strip() for host in os.environ.get("DJANGO_ALLOWED_HOSTS", "localhost,127.0.0.1,testserver" if DEBUG else "").split(",") if host.strip()]
CSRF_TRUSTED_ORIGINS = [origin.strip() for origin in os.environ.get("DJANGO_CSRF_TRUSTED_ORIGINS", "").split(",") if origin.strip()]
INSTALLED_APPS = [
    "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes",
    "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles",
    'shop', 'tasks', 'orders',
]
MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "whitenoise.middleware.WhiteNoiseMiddleware",
    "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 = "config.urls"
TEMPLATES = [{
    "BACKEND": "django.template.backends.django.DjangoTemplates",
    "DIRS": [BASE_DIR / "templates"], "APP_DIRS": True,
    "OPTIONS": {"context_processors": [
        "django.template.context_processors.request",
        "django.contrib.auth.context_processors.auth",
        "django.contrib.messages.context_processors.messages",
    ]},
}]
WSGI_APPLICATION = "config.wsgi.application"
DATABASE_URL = os.environ.get("DATABASE_URL", "")
if DATABASE_URL:
    DATABASES = {"default": dj_database_url.parse(DATABASE_URL, conn_max_age=60, conn_health_checks=True)}
elif DEBUG:
    DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": BASE_DIR / "db.sqlite3"}}
else:
    raise ImproperlyConfigured("Set DATABASE_URL to a persistent PostgreSQL database")
AUTH_PASSWORD_VALIDATORS = [
    {"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"},
    {"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"},
    {"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"},
    {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"},
]
LANGUAGE_CODE = "en-us"
TIME_ZONE = "Asia/Kolkata"
USE_I18N = True
USE_TZ = True
STATIC_URL = "/static/"
STATIC_ROOT = BASE_DIR / "staticfiles"
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
LOGIN_URL = "login"
LOGIN_REDIRECT_URL = "tasks:list"
LOGOUT_REDIRECT_URL = "shop:home"

STORAGES = {
    "default": {"BACKEND": "django.core.files.storage.FileSystemStorage"},
    "staticfiles": {"BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage"},
}
if not DEBUG:
    SESSION_COOKIE_SECURE = True
    CSRF_COOKIE_SECURE = True
    SECURE_SSL_REDIRECT = True
    # Enable only behind Render's trusted HTTPS-terminating proxy.
    if os.environ.get("TRUST_PROXY", "0") == "1":
        SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
    SECURE_HSTS_SECONDS = 3600
    SECURE_HSTS_INCLUDE_SUBDOMAINS = False
    SECURE_HSTS_PRELOAD = False

Read the code

  1. When DJANGO_DEBUG=0, a secret and database URL are mandatory. ALLOWED_HOSTS contains hostnames without a scheme; trusted CSRF origins include https://.
  2. WhiteNoise follows SecurityMiddleware. collectstatic produces hashed assets using the configured staticfiles storage backend.
  3. Secure cookies and HTTPS redirects are enabled in production. TRUST_PROXY enables recognition of Render’s trusted proxy only; do not trust arbitrary forwarded headers on an unprotected direct server.
  4. HSTS is initially short and does not opt in every subdomain. Confirm HTTPS behavior before raising its duration.

.env.example

Document live configuration names without distributing credentials.

.env.example
DJANGO_DEBUG=0
DJANGO_SECRET_KEY=generate-a-long-random-value-do-not-use-this-placeholder
DATABASE_URL=postgresql://USER:PASSWORD@HOST:5432/DATABASE
DJANGO_ALLOWED_HOSTS=your-service.onrender.com
DJANGO_CSRF_TRUSTED_ORIGINS=https://your-service.onrender.com
TRUST_PROXY=1

Read the code

  1. Enter actual values in your hosting environment. The source code does not load this file automatically.
  2. Use the provider’s required TLS options in DATABASE_URL where applicable; do not disable certificate checks to hide a connection failure.

build.sh

Install dependencies and prepare static assets during a deploy build.

build.sh
#!/usr/bin/env bash
set -o errexit
python -m pip install -r requirements.txt
python manage.py collectstatic --noinput

Read the code

  1. bash build.sh avoids relying on executable permissions when a ZIP is extracted.
  2. Database migrations are a separate release/pre-deploy command so a failed build does not silently change schema.

4. Run it and check your result

  • Development tests still pass after adding deployment dependencies.
  • Production settings reject a missing secret or missing persistent database URL.
  • collectstatic succeeds and check --deploy is reviewed with the intended production environment.

5. Predict, change and observe

Set DJANGO_DEBUG=0 without providing a secret key.

Compare your prediction with the expected result

What you should observe

Settings initialization refuses to start.

Why it happens

A production process must not silently use the publicly known development key. Failing early makes the missing configuration visible.

6. Troubleshoot with evidence

A common mistake

Do not run runserver as the public production process, and do not switch off CSRF or allow every hostname to bypass configuration mistakes.

DisallowedHost

Likely cause: The request hostname is not listed in ALLOWED_HOSTS.

Check and correct: Set DJANGO_ALLOWED_HOSTS to the exact host without https:// or paths; restart the service.

CSRF origin check fails on live POST

Likely cause: The public HTTPS origin or proxy scheme configuration is wrong.

Check and correct: Add the exact https origin to DJANGO_CSRF_TRUSTED_ORIGINS and verify the trusted proxy setting.

7. Practice and explain it back

Your independent task

Explain why db.sqlite3 and uploaded files on an ephemeral web server are not durable production storage.

Attempt these questions before opening the explanations. Use the source above to justify your answer.

Does copying .env.example activate its settings?

No. This project uses os.environ directly and has no dotenv loader. Export variables or configure the host’s environment dashboard.

Why collectstatic during build instead of storing generated assets manually?

Build output is derived from versioned sources and dependencies. Rebuilding it consistently produces the correct hashed filenames and manifest for each release.