DjangoPython

Deploy a Django app

Run Django in production with Gunicorn in a container built from your Dockerfile, static files served by WhiteNoise, managed Postgres and a Celery worker. This guide takes a new project to a production deploy on Modelence.

Last updated /Tested with Django 6.1.3, Gunicorn 27.0.1, Celery 5.7.0 and Python 3.12.3

To deploy a Django app, run it under Gunicorn in a container that reads its secret key, hostnames and database URL from environment variables, and collect its static files when the image is built so WhiteNoise can serve them. Modelence is a managed cloud on AWS that builds that container from your Dockerfile, runs it in one of 17 regions next to managed MongoDB, Postgres and Redis, and deploys it with one command.

Django comes with an ORM, migrations, an admin and forms with CSRF protection, so most of the work of putting it online happens in settings.py. This guide builds a small Django app with a form, a Postgres database and a Celery task, makes its settings safe for production, writes the Dockerfile and modelence.config.json and deploys it. Along the way it covers the three problems people run into most after a first deploy: the "Bad Request (400)" page, failed CSRF checks and pages without CSS. If you already have a Django project, skip to Make the settings ready for production.

Django on Modelence at a glance

How Django runs
Gunicorn serves the WSGI app with two worker processes, in a container built from your Dockerfile
Static files
collectstatic runs during the image build, and WhiteNoise serves the hashed files with far-future cache headers
Hosts and HTTPS
ALLOWED_HOSTS reads the environment's hostname from SITE_URL, and X-Forwarded-Proto tells Django a request came over HTTPS
Databases
Managed MongoDB, Postgres and Redis in the app's region. dj-database-url turns DATABASE_URL into Django's DATABASES
Background jobs
A Celery worker runs as a second service from the same image, with managed Redis as its broker
Regions and backups
17 AWS regions, with production databases backed up at least every 6 hours in the region you pick
Price
Free plan to start. Postgres, Redis and a worker need a paid plan, from $20 a month with $20 of usage included

Before you start

  • Python 3.12 or newer, which Django 6.1 requires
  • Docker, optionally, to build and run the image on your machine before you deploy
  • Node.js, only to run the npx modelence command. The app itself doesn't use it
  • A Modelence account, which you can create for free. The Postgres database, Redis and Celery worker in this guide need a paid plan
  • Optionally, Claude Code, Cursor or Codex, if you'd rather have your coding agent write the Dockerfile and config and run the deploy

Create a Django project

Create a virtual environment, install Django with the packages production needs, and start a project called mysite with one app called notes:

mkdir notes && cd notes
python3 -m venv .venv
source .venv/bin/activate
pip install django gunicorn whitenoise dj-database-url "psycopg[binary]" "celery[redis]"
django-admin startproject mysite .
python manage.py startapp notes
pip freeze > requirements.txt

Gunicorn is the production server, WhiteNoise serves static files from it, dj-database-url reads the database from a URL and psycopg is the Postgres driver. Install Celery with its redis extra rather than celery and redis on their own: the extra also installs packaging, which the Redis transport in Kombu 5.7 imports, and without it the first .delay() call fails with ModuleNotFoundError: No module named 'packaging'. pip freeze pins the versions you installed in requirements.txt, so the image installs the same ones.

Add a page, a health route and a task

Add "notes" to INSTALLED_APPS in mysite/settings.py. The app stores notes in the database, and each new note queues a Celery task:

# notes/models.py
from django.db import models


class Note(models.Model):
    text = models.CharField(max_length=200)
    created = models.DateTimeField(auto_now_add=True)
# notes/tasks.py
from celery import shared_task

from .models import Note


@shared_task
def note_added(note_id):
    note = Note.objects.get(id=note_id)
    print(f"Note {note.id} added: {note.text}")

The page is a form with {% csrf_token %} in notes/templates/notes/index.html and a stylesheet loaded with {% static 'notes/style.css' %}, so a deploy shows quickly whether CSRF and static files work. Route / to the page and /health to the health view in mysite/urls.py:

from django.contrib import admin
from django.urls import path

from notes import views

urlpatterns = [
    path("", views.index, name="index"),
    path("health", views.health),
    path("admin/", admin.site.urls),
]

Celery finds the tasks through mysite/celery.py, which mysite/__init__.py imports with from .celery import app as celery_app:

import os

from celery import Celery

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")

app = Celery("mysite")
app.config_from_object("django.conf:settings", namespace="CELERY")
app.autodiscover_tasks()

Then create the table's migration with python manage.py makemigrations notes.

notes/views.py
from django.http import JsonResponse
from django.shortcuts import redirect, render

from .models import Note
from .tasks import note_added


def index(request):
    if request.method == "POST":
        note = Note.objects.create(text=request.POST["text"])
        note_added.delay(note.id)
        return redirect("index")
    return render(request, "notes/index.html", {"notes": Note.objects.order_by("-created")[:20]})


def health(request):
    return JsonResponse({"status": "ok"})

Make the settings ready for production

startproject writes settings for your machine: a secret key in the file, DEBUG = True and an empty ALLOWED_HOSTS. Replace that part of mysite/settings.py with settings read from the environment, as below.

  • DEBUG is off unless DJANGO_DEBUG=1 is set, so a deploy can never run with the debug page on by accident.
  • SECRET_KEY comes from DJANGO_SECRET_KEY, which you declare as a secret, and only a debug run on your machine falls back to a placeholder.
  • ALLOWED_HOSTS decides which Host headers Django answers. Any other host gets the plain "Bad Request (400)" page, which is what a first deploy shows when the platform's hostname is missing. Modelence sets SITE_URL to the environment's address, such as https://<app>-<environment>.cloud.modelence.app, so its hostname is added automatically. Custom domains go in DJANGO_ALLOWED_HOSTS, without https:// and without a trailing slash.
  • CSRF_TRUSTED_ORIGINS takes the same hosts with https:// in front, because Django compares the full origin, scheme included, when it checks a form post.
  • SECURE_PROXY_SSL_HEADER makes Django trust the X-Forwarded-Proto header from the load balancer, which terminates HTTPS and talks plain HTTP to the container. Without it, Django believes every request is HTTP, builds http:// links and rejects form posts from the https:// page with "Origin checking failed".

Static files need two more changes. Add WhiteNoise to MIDDLEWARE directly after SecurityMiddleware, as 'whitenoise.middleware.WhiteNoiseMiddleware',, and tell Django where collectstatic puts the files:

STATIC_URL = "static/"
STATIC_ROOT = BASE_DIR / "staticfiles"
STORAGES = {
    "default": {"BACKEND": "django.core.files.storage.FileSystemStorage"},
    "staticfiles": {"BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage"},
}

CompressedManifestStaticFilesStorage gives each file a hashed name, such as style.c1945f2de73a.css, and WhiteNoise serves those with a cache lifetime of ten years, since a changed file gets a new name.

mysite/settings.py
# Production unless DJANGO_DEBUG=1 is set, which only your machine does.
DEBUG = os.environ.get("DJANGO_DEBUG") == "1"

SECRET_KEY = os.environ.get("DJANGO_SECRET_KEY") or ("django-insecure-dev" if DEBUG else "")

ALLOWED_HOSTS = ["localhost", "127.0.0.1"]
# SITE_URL is the environment's address, set by Modelence.
if site_url := os.environ.get("SITE_URL"):
    ALLOWED_HOSTS.append(urlparse(site_url).hostname)
# Custom domains, comma-separated: example.com,www.example.com
ALLOWED_HOSTS += [h.strip() for h in os.environ.get("DJANGO_ALLOWED_HOSTS", "").split(",") if h.strip()]
CSRF_TRUSTED_ORIGINS = [f"https://{host}" for host in ALLOWED_HOSTS]

# The load balancer terminates HTTPS and says so in X-Forwarded-Proto.
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
SESSION_COOKIE_SECURE = not DEBUG
CSRF_COOKIE_SECURE = not DEBUG

Run the app locally

Create the tables and start the development server with debug on. Without DATABASE_URL the app uses a local SQLite file, and without REDIS_URL Celery tasks run inline, so nothing else needs to be running:

export DJANGO_DEBUG=1
python manage.py migrate
python manage.py runserver

Open http://localhost:8000, add a note, and the task's output appears in the terminal.

To try the production settings before you write the Dockerfile, turn debug off, collect the static files and start Gunicorn the way the container will:

unset DJANGO_DEBUG
export DJANGO_SECRET_KEY=$(python -c "import secrets; print(secrets.token_urlsafe(50))")
python manage.py collectstatic --noinput
gunicorn mysite.wsgi --bind 0.0.0.0:8000 --workers 2 --access-logfile -

The page should load with its stylesheet, and http://localhost:8000/admin/ should show the styled admin login. If it shows without styling, WhiteNoise isn't in MIDDLEWARE or collectstatic didn't run.

Add a database

  • MongoDBMONGODB_URI
  • PostgresDATABASE_URL
  • RedisREDIS_URL

For Django, a managed MongoDB, Postgres or Redis on Modelence is a connection string in an environment variable. Postgres reaches the app as DATABASE_URL, of the form postgresql://...?sslmode=require, and dj-database-url turns it into Django's DATABASES setting, sslmode included, so connections use TLS:

DATABASES = {
    "default": dj_database_url.config(
        default=f"sqlite:///{BASE_DIR / 'db.sqlite3'}",
        conn_max_age=600,
        conn_health_checks=True,
    )
}

conn_max_age=600 keeps a connection open for up to ten minutes instead of opening one per request, and conn_health_checks replaces a connection that dropped, for example while a database fails over to a healthy machine. The SQLite default only applies on your machine, because a deployed environment always sets DATABASE_URL. Production databases are backed up at least every six hours.

Redis reaches the app as REDIS_URL, a rediss:// URL, which the Celery settings under Production readiness use as the broker. For MongoDB, add "db": { "type": "mongodb" } to resources, and the connection string arrives as MONGODB_URI for PyMongo or the official django-mongodb-backend package. A Postgres you already run on Supabase or Neon keeps working once its URL is declared in env with "type": "secret".

Run migrations before you deploy

Leave migrations out of the Dockerfile's CMD and the service's start, because every container runs those when it starts, several at once during a rollout, and the health check can kill a slow migration partway through. Run migrate against the environment's database before you deploy instead:

DATABASE_URL="<the environment's Postgres URL>" python manage.py migrate

The previous version keeps serving until the new containers pass their health check, so for a short time old code runs against the new schema. Make each migration one the old code can live with, such as adding a nullable column, and drop columns in a later deploy once no code reads them.

Postgres and Redis are declared as resources in modelence.config.json, and the deploy creates them before the new version starts:

modelence.config.json
{
  "resources": {
    // "web" and "worker": the app's services, as in the next steps
    "main-db": { "type": "postgres", "plan": "postgres-1gb" },
    "queue": { "type": "redis" }
  },
  "env": {
    "DATABASE_URL": { "type": "resource", "resource": "main-db", "output": "url" },
    "REDIS_URL": { "type": "resource", "resource": "queue", "output": "url" }
  }
}

Write a Dockerfile

A Python app on Modelence is built from its own Dockerfile, the same way as in the FastAPI guide, and Deploy a Docker app covers what any container needs. Add this one at the root of the project:

  • The base image comes from public.ecr.aws/docker/library/, a mirror of Docker Hub's official images, because Docker Hub limits how often images can be pulled and a build can fail on a plain FROM python:3.12-slim.
  • requirements.txt is copied and installed before the code, so a code change doesn't reinstall the packages.
  • collectstatic runs in the build, so the hashed files are part of the image. It needs neither DJANGO_SECRET_KEY nor DATABASE_URL, which a build doesn't have.
  • Gunicorn binds to 0.0.0.0:8000. Its default, 127.0.0.1, accepts connections only from inside the container, so the load balancer and the health check would never reach it.
  • CMD uses the exec form, so the stop signal reaches Gunicorn rather than a shell, and --access-logfile - writes one line per request to the logs.

Add a .dockerignore next to it, so the virtual environment, local static files and the SQLite file stay out of the build:

.git
.venv
__pycache__
staticfiles
db.sqlite3
.env
Dockerfile
FROM public.ecr.aws/docker/library/python:3.12-slim
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
RUN python manage.py collectstatic --noinput
CMD ["gunicorn", "mysite.wsgi", "--bind", "0.0.0.0:8000", "--workers", "2", "--access-logfile", "-"]

Describe the app in modelence.config.json

Add modelence.config.json at the root of the repository and commit it with the app and the Dockerfile. It describes two services built from the same Dockerfile, the database and Redis:

  • web runs the Dockerfile's CMD, listens on port 8000 and is healthy once /health answers. It comes first, so the first deploy attaches the environment's URL to it.
  • worker replaces CMD with the Celery command through start. It listens on no port, so it has no health check, and "rollout": "recreate" stops the old worker before the new one starts.
  • DJANGO_SECRET_KEY is a secret with no value in the file. The deploy asks for it, and you can view or change it later in the dashboard, where every view is logged.
  • DJANGO_ALLOWED_HOSTS is optional, for custom domains.
modelence.config.json
{
  "$schema": "https://cloud.modelence.com/schema/modelence.config.json?version=1",
  "resources": {
    "web": {
      "type": "service",
      "dockerfile": "Dockerfile",
      "ports": [8000],
      "healthCheck": { "type": "http", "path": "/health" }
    },
    "worker": {
      "type": "service",
      "dockerfile": "Dockerfile",
      "start": { "commands": ["celery -A mysite worker --loglevel=info"] },
      "healthCheck": { "type": "none" },
      "rollout": "recreate"
    },
    "main-db": { "type": "postgres", "plan": "postgres-1gb" },
    "queue": { "type": "redis" }
  },
  "env": {
    "DATABASE_URL": { "type": "resource", "resource": "main-db", "output": "url" },
    "REDIS_URL": { "type": "resource", "resource": "queue", "output": "url" },
    "DJANGO_SECRET_KEY": { "type": "secret" },
    "DJANGO_ALLOWED_HOSTS": { "required": false }
  }
}

Adjust the config for your project

  • Replace mysite in the Dockerfile's CMD and in the worker's start with the package that holds your wsgi.py and celery.py.
  • Set the Python version in the FROM line to the one the project uses, 3.12 or newer for Django 6.1.
  • --workers 2 runs two Gunicorn processes, which took about 150 MB together in our test. On a larger container, which you pick under Configure in the dashboard, raise it. To change it without a rebuild, remove --workers from CMD and set WEB_CONCURRENCY in the dashboard, which Gunicorn reads as its default.
  • For async views or an ASGI app, add uvicorn-worker to requirements.txt and start gunicorn mysite.asgi:application -k uvicorn_worker.UvicornWorker --bind 0.0.0.0:8000, which serves the same app, health route and static files.
  • A Dockerfile service can't use static mounts, which is why WhiteNoise serves /static/ from Gunicorn here. Uploaded media files belong in object storage, as under Production readiness.
  • Declare other keys, such as SMTP credentials or a Stripe key, with "type": "secret" and no value, and read them with os.environ.
  • If the Django project lives in a subdirectory, such as backend/, set "root": "backend" on both services. The dockerfile path is relative to it, and the build sees only the files under it.

Check the build locally

With Docker installed, build the image and run it with the variables a deploy provides. Without DATABASE_URL the container falls back to an empty SQLite file, so check /health and a static file rather than the page:

docker build -t notes .
docker run --rm -e PORT=8000 -e DJANGO_SECRET_KEY=local-check -p 8000:8000 notes

Then open http://localhost:8000/health and http://localhost:8000/static/admin/css/base.css. A deploy runs the same build, so anything that fails here fails there too.

Deploy

Run the deploy command in the project directory:

npx modelence@latest deploy

It opens the browser, where you sign in, pick the organization, app and environment (or create them) and enter the variables the environment doesn't have yet. For DJANGO_SECRET_KEY, paste the output of python -c "import secrets; print(secrets.token_urlsafe(50))". Then it uploads the project, builds both services and follows the build until they are live. You pick the AWS region the first time you deploy an environment, and its containers and databases are created there.

The first deploy creates the Postgres database and Redis, starts web and worker once they are ready and attaches <app>-<environment>.cloud.modelence.app to port 8000 of web. The database starts empty, so run migrate against it as described in Add a database before you use the app. From then on, run new migrations before each deploy.

To use your own domain, add it in the dashboard under Domains, add its hostname to DJANGO_ALLOWED_HOSTS under Environment variables and deploy again, since containers read their variables when they start.

Let your coding agent do it

Paste Deploy using https://modelence.com/skill.md into Claude Code, Cursor or Codex in your project. The agent reads the docs, writes the Dockerfile and modelence.config.json for your project, checks the build and runs the deploy, and it stops to ask you whenever a step needs your account.

Production readiness

Run the deploy checks

python manage.py check --deploy lists settings that are unsafe in production. With the settings in this guide it reports two warnings. security.W008 suggests SECURE_SSL_REDIRECT, which you can leave off, because Modelence already redirects plain HTTP to HTTPS before a request reaches Django. security.W004 suggests HSTS, which you can turn on with SECURE_HSTS_SECONDS once every domain the app uses serves HTTPS.

Django 6.1's startproject also sets MAILERS to the console backend, and check --deploy reports that as an error, since email would only be printed. Keep the console backend for debug runs and send real email over SMTP otherwise, with the credentials declared as secrets:

MAILERS = {
    "default": {
        "BACKEND": "django.core.mail.backends.console.EmailBackend",
    }
    if DEBUG
    else {
        "BACKEND": "django.core.mail.backends.smtp.EmailBackend",
        "OPTIONS": {
            "host": os.environ.get("SMTP_HOST"),
            "port": 587,
            "username": os.environ.get("SMTP_USER"),
            "password": os.environ.get("SMTP_PASSWORD"),
            "use_tls": True,
        },
    },
}

Add a health check

With "healthCheck": { "type": "http", "path": "/health" }, a container counts as healthy once /health answers with a 2xx status within 4 seconds, so a version that starts but can't serve requests never takes traffic and the deploy rolls back. The health view in this guide doesn't query the database, so a short database failover doesn't get healthy containers replaced.

The check sends the same Host header as real traffic, the environment's hostname, which is why ALLOWED_HOSTS has to include it. If it didn't, every check would get a 400 and no version would ever become healthy. When the environment's URL isn't attached to web, the check uses the service's private hostname instead, such as web.<environment id>.cloud.local:8000, so add .cloud.local to DJANGO_ALLOWED_HOSTS. The leading dot matches every subdomain, and Django ignores the port.

Shut down without dropping requests

When a container stops, for example during a deploy, Gunicorn gets SIGTERM, and SIGKILL follows after stopTimeout, 30 seconds by default. Gunicorn closes its listening socket at once, lets each worker finish the request it is handling and then exits. In our test, a 5-second request that was running when the signal arrived completed with a 200, and an idle server exited in under a second.

The load balancer can still send new requests for about 10 seconds after SIGTERM, and those fail once the socket is closed. To serve them too, start Gunicorn from a small script that waits 10 seconds before passing the signal on:

# start.sh
#!/bin/sh
# Modelence keeps sending requests to a stopping container for about
# 10 seconds after SIGTERM, so Gunicorn keeps serving for that long.
gunicorn mysite.wsgi --bind 0.0.0.0:${PORT:-8000} --workers 2 --access-logfile - &
pid=$!
trap 'sleep 10; kill -TERM $pid' TERM
wait $pid
wait $pid

Make it executable with chmod +x start.sh, set CMD ["./start.sh"] in the Dockerfile and give web "stopTimeout": 45, which covers the 10-second wait plus Gunicorn's own graceful timeout of 30 seconds. In our test, requests sent during those 10 seconds were all answered, and Gunicorn exited about a second later.

Run Celery as its own service

Don't start a Celery worker or a scheduler inside the web container. With two web containers, each would run every job and emails would go out twice. The worker service in the config runs the worker on its own, and Celery reads its broker from these settings:

CELERY_BROKER_URL = os.environ.get("REDIS_URL", "redis://localhost:6379/0")
if CELERY_BROKER_URL.startswith("rediss://"):
    CELERY_BROKER_USE_SSL = {"ssl_cert_reqs": ssl.CERT_REQUIRED}
# Without Redis on your machine, tasks run inline while you develop.
CELERY_TASK_ALWAYS_EAGER = DEBUG and "REDIS_URL" not in os.environ

Modelence's Redis URL starts with rediss://, so the connection uses TLS. Celery 5.7 accepts such a URL without SSL options but then skips certificate verification and logs a warning, and CELERY_BROKER_USE_SSL with CERT_REQUIRED turns verification on.

On SIGTERM, Celery does a warm shutdown, finishing the tasks it is running before it exits. A task that can take longer than stopTimeout should be safe to run again. For periodic tasks, add one more service with celery -A mysite beat as its start command, "rollout": "recreate" and one container, since two schedulers would queue every task twice. Multiple services has the details.

Keep files and state out of the container

A container's disk is replaced on every deploy, so the app keeps its data in Postgres or MongoDB, and the SQLite fallback is only for your machine. Files that users upload through a FileField or ImageField need object storage, for example S3 through django-storages, set as the default entry of STORAGES. Static files are fine where they are, since they are rebuilt into every image.

Django's default session backend stores sessions in the database, so they work across containers and deploys as they are. With state out of the containers, two or more web containers under Configure keep the app up when one crashes or a zone goes down. See Availability for how rollouts and rollbacks behave.

Send errors to the logs

Everything the app writes to its output shows on the environment's Logs page, including Gunicorn's access log. Django's default logging, however, prints errors to the console only while DEBUG is on, so in production a 500 or a rejected Host header leaves no trace there. Add a LOGGING setting that sends everything at INFO and above to the console:

# Send errors and Django's warnings, such as a rejected Host header, to the logs.
LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "handlers": {"console": {"class": "logging.StreamHandler"}},
    "root": {"handlers": ["console"], "level": "INFO"},
}

A wrong host then logs Invalid HTTP_HOST header: 'example.com'. You may need to add 'example.com' to ALLOWED_HOSTS. with the exact name to add.

Modelence vs Heroku, Render and Railway for Django

Django developers most often weigh Heroku, Render and Railway, and each of them has an official Django guide. The table is based on each platform's own docs and pricing pages as of November 2026.

PlatformHow Django runsMigrationsPricing
ModelenceGunicorn in a container built from your Dockerfile, in 17 AWS regions, with managed MongoDB, Postgres and Redis in the same regionYou run migrate against the environment's database before you deploy, since there is no release phaseFree plan, then from $20 a month with that amount included as usage
HerokuThe Python buildpack installs your requirements and runs collectstatic during the build, and a Procfile line such as web: gunicorn myproject.wsgi starts the dyno. The Common Runtime runs in the US or EuropeA release: python manage.py migrate line runs before each release, and a failure stops the releaseEco dynos $5 a month, which sleep after 30 idle minutes, Basic $7; Postgres from $5 and Key-Value Store from $3 a month
RenderNative Python runtime with a build script that runs collectstatic, and Gunicorn with Uvicorn workers as the start command, in 5 regions (Oregon, Ohio, Virginia, Frankfurt and Singapore)Its Django guide runs migrate in the build script, and paid services can use a pre-deploy commandWorkspace plan (Hobby free, Pro $25 a month) plus instances from $7 a month. Free web services spin down after 15 idle minutes, and free Postgres expires after 30 days
RailwayDetects the Django app and builds it from the repository, in 4 regions (California, Virginia, Amsterdam and Singapore). Its guide runs the Celery worker and beat as separate servicesA pre-deploy command runs after the build, and the deploy stops if it failsFree with $1 of usage a month, Hobby $5 or Pro $20 a month including that much usage, billed by the second

Heroku is the most familiar path for Django, with a buildpack that needs no Dockerfile and a release phase that runs migrations for you, which also makes it the easiest to follow from older tutorials. Render's native Python runtime and fixed instance prices suit a team that wants a predictable bill without writing a Dockerfile, and Railway is quick to start on and cheap for services that sit idle much of the day. Modelence fits a Django app with a web service, Celery workers, Postgres and Redis that should run on AWS with backups in a region you choose out of 17, and it lets a coding agent write the config and run the deploy. Heroku alternatives, Railway vs Render and Render alternatives compare these platforms in more depth, and Move from Railway covers a migration.

Next steps

Frequently asked questions

How do I deploy a Django app to production?

Run it under a production server such as Gunicorn, with DEBUG off, the secret key and database URL read from environment variables, ALLOWED_HOSTS set to your domains and static files collected and served by WhiteNoise or a CDN. On Modelence you add a Dockerfile that installs requirements.txt, runs collectstatic and starts Gunicorn, describe the app and its database in modelence.config.json and run npx modelence@latest deploy, which builds the image and runs it as containers on AWS.

Why does my deployed Django app show "Bad Request (400)"?

Django returns that page when the request's Host header isn't in ALLOWED_HOSTS, which is the most common problem after a first deploy. Add the platform's hostname and every custom domain as bare hostnames, without https:// or a trailing slash. On Modelence the environment's address is in the SITE_URL variable, so the settings can add its hostname automatically, and a LOGGING setting that writes to the console makes Django log the exact host it rejected.

Why do I get "CSRF verification failed" after deploying Django?

Behind a load balancer, Django usually believes the request came over plain HTTP, so it rejects a form post from the https:// page with "Origin checking failed". Set SECURE_PROXY_SSL_HEADER to ("HTTP_X_FORWARDED_PROTO", "https") so Django trusts the load balancer's header, and list your domains with their scheme, such as https://example.com, in CSRF_TRUSTED_ORIGINS.

Why are my static files missing when DEBUG is False?

Django serves static files only in debug mode, so in production something else has to serve the files that collectstatic gathers into STATIC_ROOT. The simplest option is WhiteNoise, added to MIDDLEWARE right after SecurityMiddleware, with collectstatic run while the image is built. With CompressedManifestStaticFilesStorage it serves hashed file names with long cache lifetimes straight from Gunicorn.

Where should Django migrations run when I deploy?

Run them once per deploy, before the new code starts, and never in every container's start command, where several containers would run them at once. Heroku, Render and Railway each have a release or pre-deploy step for this. Modelence has none, and its docs say to run python manage.py migrate against the environment's database before you deploy, with migrations the previous version can keep running against.

Should I run Django with Gunicorn or Uvicorn?

Use Gunicorn with its default sync workers for a regular WSGI Django app, which is what startproject creates. For async views, WebSockets through Channels or other ASGI features, keep Gunicorn as the process manager and give it Uvicorn workers from the uvicorn-worker package: gunicorn mysite.asgi:application -k uvicorn_worker.UvicornWorker. Never use manage.py runserver in production, since it is a development server.

How do I run Celery workers with Django on Modelence?

Run the worker as a second service in modelence.config.json, built from the same Dockerfile, with start set to celery -A mysite worker, no health check and "rollout": "recreate". A managed Redis resource is the broker, and its rediss:// URL reaches both services as REDIS_URL. Celery beat goes in a third service with a single container, so scheduled tasks aren't queued twice.

Can I deploy Django on Vercel?

Yes, Vercel detects manage.py and runs the whole Django app as a single Vercel Function, with collectstatic run automatically when STATIC_ROOT is set and the files served from its CDN. A request can run for 300 seconds by default and 800 seconds at most on Pro, and Celery tasks run through queue-triggered functions. An app that needs long-running Gunicorn processes and an always-on Celery worker next to its own Postgres and Redis fits better on a container platform such as Modelence.

Can I use SQLite for a Django app in production?

Not on Modelence or any platform that replaces containers on each deploy, because the SQLite file lives on the container's disk and is lost with it. Use the managed Postgres instead, which dj-database-url reads from DATABASE_URL, and keep SQLite as the fallback on your own machine. The Postgres database is backed up at least every six hours.

How much does it cost to host a Django app on Modelence?

You can start on the free plan, which runs one instance that sleeps when idle. Managed Postgres and Redis and a second service, such as a Celery worker, need a paid plan, which starts at $20 a month with the same amount included as cloud usage, and you pay only for usage above that.

Deploy other stacks

Deploy your Django app

Start on the free plan and move up when your app needs more.

Or paste this into your coding agent