Deploy Django with PostgreSQL

Deploy a Django app on Hangar with gunicorn, a managed PostgreSQL database, migrations on every release and static files served by WhiteNoise.

Updated

Markdown

Skip the setup

Deploy a working starter of this guide, on its own URL, in one click.

Deploy on Hangar

This guide deploys a Django project with gunicorn as the server and a managed PostgreSQL database, both on Hangar, talking over the private network. A hangar.yaml file in the repository describes both, so one link creates the database, wires it to the app and deploys.

Prepare the project#

Four changes make a Django project ready for production anywhere. If yours already has them, skip ahead.

Dependencies#

Add the production packages to requirements.txt:

requirements.txt
gunicorn
psycopg[binary]
dj-database-url
whitenoise

Settings from the environment#

Python
# settings.py
import os
import dj_database_url

SECRET_KEY = os.environ["SECRET_KEY"]
DEBUG = os.environ.get("DEBUG") == "1"
ALLOWED_HOSTS = os.environ.get("ALLOWED_HOSTS", "").split(",")
CSRF_TRUSTED_ORIGINS = [f"https://{host}" for host in ALLOWED_HOSTS if host]

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

dj_database_url.config() reads DATABASE_URL.

Static files#

Python
# settings.py
MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "whitenoise.middleware.WhiteNoiseMiddleware",
    # ...
]
STATIC_ROOT = BASE_DIR / "staticfiles"

HTTPS behind the proxy#

Hangar terminates TLS and forwards the request to your app, so tell Django to trust the forwarded protocol:

Python
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")

1Add hangar.yaml#

Create hangar.yaml at the root of the repository, next to manage.py:

YAML
# yaml-language-server: $schema=https://tryhangar.io/schema/hangar.v1.json
version: 1
name: My Django app
services:
  web:
    preDeploy: python manage.py migrate
    start: python manage.py collectstatic --noinput && gunicorn mysite.wsgi --bind 0.0.0.0:$PORT
    env:
      DATABASE_URL: ${{ db.url }}
      SECRET_KEY:
        generate: secret
      ALLOWED_HOSTS: ${{ web.host }}
databases:
  db:
    kind: postgres

Replace mysite with the name of your project package. What each part does:

  • databases.db creates a managed PostgreSQL database in the same region as the app.
  • DATABASE_URL: ${{ db.url }} fills in the database's internal connection URL.
  • SECRET_KEY gets a long random value, made once when the project is created.
  • ALLOWED_HOSTS: ${{ web.host }} allows the address Hangar gives the service, and the settings above derive CSRF_TRUSTED_ORIGINS from it.
  • preDeploy migrates the database on every deploy, before the new version takes traffic. A failed migration stops the deploy and the running version stays up.
  • start collects static files and starts gunicorn on the port Hangar sets in PORT, on 0.0.0.0 so the proxy can reach it.

The builder needs no setting: the automatic builder detects Python from requirements.txt (or pyproject.toml) and installs the dependencies. Every key is explained in the hangar.yaml reference.

Push the file and open the deploy link for your repository:

Text
https://tryhangar.io/deploy?repo=https://github.com/owner/name

The page lists what the manifest creates, a service and a PostgreSQL database. Pick a region and deploy. Put the same link in your README as a Deploy on Hangar button and anyone can do the same.

The manifest is read once, when the project is created. From then on the service is configured in the dashboard, and every push to the branch deploys it again.

3Add a domain#

In the service's Settings → Networking, add your hostname with HTTPS on. Then, in the Variables tab, append it to ALLOWED_HOSTS after the generated address, separated by a comma, and redeploy.

Without a manifest#

Deploy links need a public repository. For a private one, connect your Git provider and set up the same thing from the dashboard:

  1. In a new project, add a PostgreSQL service and pick a region. When it is running, open it and copy the internal connection URL.
  2. Add a service from your repository, in the same region as the database. Leave the builder on Automatic.
  3. In the service's Variables tab, set SECRET_KEY to a long random string, ALLOWED_HOSTS to your hostname and DATABASE_URL to the internal connection URL. Generate the key locally with python -c "import secrets; print(secrets.token_urlsafe(50))".
  4. In Settings → Runtime, set the pre-deploy command to python manage.py migrate. The start command chains two commands, so it runs through a shell: set it to sh with two arguments, -c and python manage.py collectstatic --noinput && gunicorn mysite.wsgi --bind 0.0.0.0:$PORT.
  5. Deploy, then add your hostname in Settings → Networking with HTTPS on.

Background workers#

Celery or another worker runs as a second service from the same repository. In hangar.yaml, add it next to web without a public address, with a Redis database as the broker:

YAML
services:
  web:
    # preDeploy, start and env as above, plus:
    env:
      REDIS_URL: ${{ broker.url }}
  worker:
    public: false
    start: celery -A mysite worker --loglevel=info
    env:
      DATABASE_URL: ${{ db.url }}
      REDIS_URL: ${{ broker.url }}
databases:
  db:
    kind: postgres
  broker:
    kind: redis

Troubleshooting#

  • DisallowedHost: the domain is missing from ALLOWED_HOSTS.
  • CSRF verification failed on forms: the https:// origin is missing from CSRF_TRUSTED_ORIGINS.
  • connection refused to the database: the app and the database are in different regions, or DATABASE_URL holds an external address instead of the internal one.

Frequently asked questions

How do I run Django migrations on Hangar?
Set python manage.py migrate as the service's pre-deploy command, as preDeploy in hangar.yaml or in Settings → Runtime. It runs in the new image on every deploy, before the new version accepts traffic, and a failed migration stops the deploy.
How does Django connect to PostgreSQL on Hangar?
Declare the database in hangar.yaml and set DATABASE_URL to ${{ db.url }}, and Hangar creates it with the app and fills in its internal connection URL. By hand, create a PostgreSQL database in the same project and paste its internal URL into DATABASE_URL. The app reaches it over the private network.
How are Django static files served on Hangar?
The simplest setup is WhiteNoise, which lets gunicorn serve the collected static files itself. Run collectstatic during the build or in the start command.