Deploying a Django application to the internet

Lesson 9 of 9 · Python web: Django project

The application works on your computer; now we put it on a server so that everyone can use it. We show two free ways – Render (PostgreSQL, automatic updates from GitHub) and PythonAnywhere (the simplest, SQLite) – and what has to be changed in the project before publishing.

Before you start: required prior knowledge – saving logos, publishing a static site.
How to learn: work in your own project step by step and after every lesson check that the server works; do the task at the end on your own first. The code is for Django 5.2 (LTS) and Python 3.12+; type each part into the file named in the comment at the top of the example.

What is different on a server

Development (your computer)Server
runs the applicationrunserverGunicorn (a WSGI server)
static filesDjango serves them itselfcollectstatic + WhiteNoise
databasean SQLite filePostgreSQL (Render) or SQLite (PythonAnywhere)
DEBUGTrueFalse
secretsin settings.pyenvironment variables
Heroku: the first version of the project was deployed to Heroku. Since November 2022 Heroku has no free plan, so for school projects we use the platforms below. The terms of free plans change – check them on the platform's website before you start.

Preparing the project

pip install gunicorn whitenoise dj-database-url "psycopg[binary]"
pip freeze > requirements.txt
# logo_kreator/settings.py – settings for running on the internet
# add AT THE END of the file; delete the existing SECRET_KEY, DEBUG, ALLOWED_HOSTS and DATABASES from the upper part
import os
import dj_database_url

SECRET_KEY = os.environ.get("SECRET_KEY", "development-only-change-me")  # on the server: an environment variable
DEBUG = os.environ.get("DEBUG", "0") == "1"                              # turned off on the server

ALLOWED_HOSTS = ["localhost", "127.0.0.1"]
RENDER_HOST = os.environ.get("RENDER_EXTERNAL_HOSTNAME")                 # Render sets it by itself
if RENDER_HOST:
    ALLOWED_HOSTS.append(RENDER_HOST)
    CSRF_TRUSTED_ORIGINS = [f"https://{RENDER_HOST}"]

# WhiteNoise serves static files (CSS, JS, images) without a separate server
MIDDLEWARE.insert(1, "whitenoise.middleware.WhiteNoiseMiddleware")      # right after SecurityMiddleware
STATIC_ROOT = BASE_DIR / "staticfiles"
STORAGES = {
    "default": {"BACKEND": "django.core.files.storage.FileSystemStorage"},
    "staticfiles": {"BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage"},
}

# database: on the server from DATABASE_URL (PostgreSQL), at home SQLite
DATABASES = {
    "default": dj_database_url.config(default=f"sqlite:///{BASE_DIR / 'db.sqlite3'}", conn_max_age=600)
}

Also make the file build.sh in the root of the project – the commands that Render runs at every deployment:

#!/usr/bin/env bash
# build.sh – Render runs it at every deployment
set -o errexit                       # stop at the first error
pip install -r requirements.txt
python manage.py collectstatic --no-input
python manage.py migrate

collectstatic gathers the CSS, JS and images of all apps (and of the admin panel) into the folder staticfiles, from where WhiteNoise serves them. Check locally: python manage.py check --deploy lists the security settings that are missing.

Render step by step

  1. Put the project on GitHub (without .venv and db.sqlite3 – see .gitignore from lesson 2).
  2. On render.com create an account and New → PostgreSQL → name logo-kreator-db → Free. Copy the Internal Database URL.
  3. New → Web Service → connect the GitHub repository.
  4. Runtime: Python, Build Command: bash build.sh, Start Command: gunicorn logo_kreator.wsgi.
  5. Environment → add the variables: DATABASE_URL (the database address from step 2), SECRET_KEY (a long random string – Render has a Generate button), PYTHON_VERSION (e.g. 3.13.1).
  6. Create Web Service – after a few minutes the application is at https://logo-kreator.onrender.com (the name depends on your service).
  7. An administrator on the server: in the service's Shell tab run python manage.py createsuperuser.

Every new git push to GitHub automatically deploys the application again. A free service "falls asleep" after a period of inactivity, so the first opening can take up to a minute.

PythonAnywhere – the simplest way

PythonAnywhere is a good choice for the first time: it has a free account, Python is already installed, and the database can stay SQLite.

  1. Create a free account (Beginner).
  2. In Consoles → Bash: git clone your repository, create .venv and run pip install -r requirements.txt.
  3. Web → Add a new web app → Manual configuration → choose the Python version; in the settings type the path to .venv and edit the WSGI file so that it loads logo_kreator.settings.
  4. In Static files map /static/ to the folder staticfiles and run python manage.py collectstatic and migrate.
  5. Add username.pythonanywhere.com to ALLOWED_HOSTS and click Reload.

Detailed instructions for Django are in their documentation.

The most common errors after deploying

SymptomCause and solution
DisallowedHost / Bad Request (400)the domain is not in ALLOWED_HOSTS
a page without CSS, the admin without stylecollectstatic was not run or WhiteNoise was not added
CSRF verification failed when signing inCSRF_TRUSTED_ORIGINS with the https:// address is missing
Server Error (500)look at the Logs on the platform; often a forgotten migration or environment variable
no such table / relation does not existmigrate was not run on the server

Video: deploying to Heroku (the first version)

Note on the video: the video is in Serbian, and Heroku no longer has a free plan. The video shows the same flow (GitHub → platform → environment variables → database), so it helps you understand the steps, but for the project follow the instructions for Render or PythonAnywhere on this page.

Practice tasks

Each task has an example, a hint and a solution.

TASK 01Difficulty: easy

A checklist before publishing

Before deploying, check the project: python manage.py check --deploy, python manage.py test, whether requirements.txt is up to date and whether .gitignore excludes .venv, db.sqlite3 and staticfiles. Write down what you had to fix.

Common mistakes and tips
  • Never deploy a project with DEBUG = True and the secret key in the code.
  • After changing a model, the migrations must be in the repository – the server only applies them (migrate), it does not create them.
  • Free services do not keep files uploaded by users (images) permanently – that is why the Logo creator keeps the logo's data in the database and draws the image from it.

Check your knowledge

Open the quiz

Deploying to the internet

1. Which program runs a Django application on the server instead of runserver?




2. What does python manage.py collectstatic do?




3. Where is SECRET_KEY kept on the server?