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.
PROJECT 8 · LESSON 15 OF 16
Replace local-only assumptions with PostgreSQL, required secrets and collected static assets.
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.
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.
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.
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.
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.
Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.
The hosted process reads environment variables before Django settings load.
Production settings require a secret, PostgreSQL URL and valid hosts.
The build installs packages and collects static assets.
The release applies versioned migrations to PostgreSQL.
Gunicorn serves Django behind the trusted HTTPS proxy; WhiteNoise serves collected assets.
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:8000The 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.
Pin the verified runtime and deployment packages.
Django==5.2.18
dj-database-url==3.1.2
whitenoise==6.12.0
gunicorn==23.0.0
psycopg[binary]==3.3.6
Separate local development defaults from required live configuration.
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
Document live configuration names without distributing credentials.
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
Install dependencies and prepare static assets during a deploy build.
#!/usr/bin/env bash
set -o errexit
python -m pip install -r requirements.txt
python manage.py collectstatic --noinput
Set DJANGO_DEBUG=0 without providing a secret key.
Settings initialization refuses to start.
A production process must not silently use the publicly known development key. Failing early makes the missing configuration visible.
Do not run runserver as the public production process, and do not switch off CSRF or allow every hostname to bypass configuration mistakes.
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.
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.
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.
No. This project uses os.environ directly and has no dotenv loader. Export variables or configure the host’s environment dashboard.
Build output is derived from versioned sources and dependencies. Rebuilding it consistently produces the correct hashed filenames and manifest for each release.