Deploying Django
Deploying means putting your Django project on a server connected to the internet so anyone can use it. This page takes the Campus Events project from your laptop to a live address: preparing settings, serving static files, running Gunicorn and publishing on a beginner-friendly host.
The deployment checklist
- Secure settings from environment variables:
DEBUG=False, a secretSECRET_KEYand the rightALLOWED_HOSTS(see Settings & Security). - An up-to-date
requirements.txt. - Static files collected with
collectstaticand served efficiently. - A production WSGI server such as Gunicorn instead of
runserver. - A database that keeps its data between deploys.
- Migrations applied on the server, and an admin user created there.
Step 1: Install production packages
python -m pip install gunicorn whitenoise python -m pip freeze > requirements.txt
- Gunicorn is a production-grade WSGI server. It runs several worker processes and handles many visitors at once.
- WhiteNoise lets your Django app serve its own static files efficiently, with compression and long-term caching, so you don't need a separate web server just for CSS.
Commit requirements.txt so your host installs exactly the same packages.
Step 2: Configure static files with WhiteNoise
Add WhiteNoise's middleware directly after SecurityMiddleware, and set the static storage:
campus/settings.py
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",
]
STATIC_URL = "static/"
STATIC_ROOT = BASE_DIR / "staticfiles"
STORAGES = {
"default": {
"BACKEND": "django.core.files.storage.FileSystemStorage",
},
"staticfiles": {
"BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage",
},
}
Then collect the files (your count and path will differ):
python manage.py collectstatic --no-input
"Post-processed" files are the hashed and compressed copies WhiteNoise creates for caching. See Static Files for the background.
Step 3: Run with Gunicorn
Gunicorn needs the path to your WSGI application: the application object in campus/wsgi.py.
gunicorn campus.wsgi
Your times, version and process IDs will differ. On a host you'll usually add options such as --bind 0.0.0.0:8000 or --workers 3, depending on its instructions.
Gunicorn runs on Linux and macOS but not on Windows. That's fine: your host runs Linux. To test a production-style server on Windows, use WSL, or try the Waitress server (waitress-serve --listen=127.0.0.1:8000 campus.wsgi:application).
Step 4: Choose a database
SQLite stores everything in one file, db.sqlite3. That's fine on hosts with a permanent disk, such as PythonAnywhere. But many modern platforms, including Render's web services, use an ephemeral filesystem: files written by your app are wiped on every deploy or restart. There, use a managed PostgreSQL database. The dj-database-url package reads its address from a DATABASE_URL environment variable:
python -m pip install dj-database-url "psycopg[binary]"
campus/settings.py
import dj_database_url
DATABASES = {
"default": dj_database_url.config(
default=f"sqlite:///{BASE_DIR / 'db.sqlite3'}",
conn_max_age=600,
)
}
Locally, with no DATABASE_URL set, you keep using SQLite. On the server, PostgreSQL is used automatically.
Step 5: Publish on a host
Hosting plans and free tiers change often, so check each provider's current plans and documentation. The overall steps look like this.
Option A: Render (deploy from GitHub)
- Push your project to a GitHub repository (without
.venv,db.sqlite3or secrets). - If you need PostgreSQL, create a database in Render first and copy its internal connection URL.
- Create a new Web Service and connect your repository.
- Set the build command and start command:
# Build command pip install -r requirements.txt && python manage.py collectstatic --no-input && python manage.py migrate # Start command gunicorn campus.wsgi
- Add environment variables:
DJANGO_SECRET_KEY(a newly generated key),DJANGO_ALLOWED_HOSTS(your.onrender.comaddress),DATABASE_URLand, if needed,PYTHON_VERSION. LeaveDJANGO_DEBUGunset so debug stays off. - Deploy, watch the build logs, then open your site's URL.
After the first deploy, every push to your main branch can trigger a new deploy automatically.
Option B: PythonAnywhere (a Python-focused host)
- Open a Bash console in your PythonAnywhere account and clone your repository with
git clone. - Create a virtual environment and run
pip install -r requirements.txt. - On the Web tab, add a new web app with manual configuration and your Python version, then enter your virtualenv path.
- Edit the WSGI configuration file linked on the Web tab so it loads your project (example below).
- Add a static files mapping: URL
/static/to the directory of yourSTATIC_ROOT, e.g./home/yourusername/campus-events/staticfiles. - Back in the console run
python manage.py migrate,collectstaticandcreatesuperuser, then click Reload.
WSGI configuration file on PythonAnywhere
import os
import sys
path = "/home/yourusername/campus-events"
if path not in sys.path:
sys.path.append(path)
os.environ["DJANGO_SETTINGS_MODULE"] = "campus.settings"
os.environ["DJANGO_SECRET_KEY"] = "paste-your-generated-key-here"
os.environ["DJANGO_ALLOWED_HOSTS"] = "yourusername.pythonanywhere.com"
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
This file lives on the server, not in your repository, so it's an acceptable place for the secret key on PythonAnywhere. Because PythonAnywhere's disk is permanent, SQLite works well for small projects there.
After you go live
- Create an admin user on the server (
python manage.py createsuperuserin the host's console or shell). Your local users don't exist in the production database. - Test everything: sign up, log in, log out, create an event, RSVP, open the admin and check that CSS loads.
- Read the logs when something breaks. With
DEBUGoff, error details go to your host's log viewer, not the browser. - Updating: push or pull the new code, install requirements, run
migrateandcollectstatic, then restart or reload.
The admin and your pages appear without any styling after deploying. This almost always means static files aren't set up: check STATIC_ROOT, run collectstatic, and make sure WhiteNoise's middleware is installed (or the static mapping is set on PythonAnywhere).
Getting 400 Bad Request on every page. Your domain is missing from ALLOWED_HOSTS. Check the exact address, without https:// or a trailing slash.
Using SQLite on a platform with an ephemeral filesystem. Everything looks fine until the next deploy, when all your users and events vanish. Use the host's PostgreSQL database instead.
Key points
- Prepare settings with environment variables:
DEBUG=False, a secret key and correctALLOWED_HOSTS. - Use WhiteNoise and
collectstaticto serve static files, and Gunicorn to run the app. - Use a database that persists: PostgreSQL on ephemeral platforms, SQLite only where the disk is permanent.
- Render deploys from GitHub with build and start commands; PythonAnywhere uses a WSGI file and static mappings.
- Run migrations, create a superuser and test every feature on the live site.
Tip: use the ← and → keys to move between pages.
