logo
Parslinks
Back to blog
Deploy5 min read

Deploying Django with PostgreSQL, without wrestling Gunicorn and Nginx

Most of Django's production problems aren't Django's. They come from static files, migrations and settings that only exist on one server.

Alireza Tadi

Co-founder, Parslinks · Team, marketing & infrastructure

A student team in Mashhad built a booking system for their faculty's study hall in Django. On their laptops, everything was perfect. On day one on a server, they set DEBUG = False and the page loaded with no CSS. After fixing that, they got "Bad Request (400)" because the domain wasn't in ALLOWED_HOSTS. A week later, after adding a field to a model, the site crashed with "column does not exist", because nobody remembered to run migrate on the server.

None of these are Django bugs. They're the places where a project moves from "on my laptop" to "on a server".

The map: where each piece goes

Where each part of a Django project goes on a VPS and on a platform

1. Settings from environment variables

One settings.py for every environment, with values read from the environment. SECRET_KEY and the database password never live in code:

config/settings.py
import os
import dj_database_url

SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]  # missing means an error, not a default
DEBUG = os.environ.get("DJANGO_DEBUG") == "1"
ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS", "").split(",")
CSRF_TRUSTED_ORIGINS = [f"https://{h}" for h in ALLOWED_HOSTS if h]

DATABASES = {"default": dj_database_url.config(conn_max_age=60)}

# Behind the platform's proxy, detect https from the header
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")

LANGUAGE_CODE = "fa"
TIME_ZONE = "Asia/Tehran"
USE_TZ = True
python16 lines

2. Gunicorn instead of runserver

runserver is for development. In production, Gunicorn runs the app. The project's start command on a platform looks something like this:

start command
gunicorn config.wsgi:application --bind 0.0.0.0:$PORT --workers 3 --timeout 60 --access-logfile -
bash1 line

Tune the worker count to the instance's resources; the common rule is two per core plus one. You don't need to put Nginx in front yourself; the proxy and SSL belong to the platform.

3. Static files with WhiteNoise

On a hand-built server, Nginx served static files from STATIC_ROOT. On a platform, WhiteNoise is the simplest route: the app serves compressed, hash-named static files with long cache headers itself. collectstatic runs during the build.

config/settings.py
MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "whitenoise.middleware.WhiteNoiseMiddleware",  # right after Security
    # ...
]
STATIC_ROOT = BASE_DIR / "staticfiles"
STORAGES = {
    "staticfiles": {"BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage"},
    "default": {"BACKEND": "storages.backends.s3.S3Storage"},  # media in object storage
}
python10 lines

The last line matters: files users upload (media) are different from static files and shouldn't stay on the app's disk. With django-storages, send them to S3-compatible object storage. We explain why in where user uploads should live.

4. Migrations, before traffic

Run python manage.py migrate as a separate step before traffic switches to the new version, not inside Gunicorn's start command; otherwise with three instances the migration runs three times at once. And write migrations compatible with the previous version: add new fields as nullable or with a default, and leave dropping fields to the next release.

5. Celery and scheduled jobs

If you hand SMS sending or report building to Celery, the worker and beat are two processes separate from the web, with the same code and variables:

ProcessCommandInstances
Webgunicorn config.wsgi:application ...As traffic requires
Celery workercelery -A config worker -l infoAs job volume requires
Celery beatcelery -A config beat -l infoExactly one

Pre-release checklist

Django has a tool for this. Before your first deploy, run it with production settings:

terminal
python manage.py check --deploy
bash1 line

Go through its warnings (secure cookies, HSTS, SSL settings) one by one. Most are a single line of config and prevent common security issues.

Frequently asked questions

Join the discussion

No comments yet. Be the first to share your thoughts.