Backend & Languages

Django Setup & Deployment Guide

Batteries-included Python web framework – project, apps, models, admin, then Gunicorn, Nginx, static files and SSL in production.

Updated Official documentation ↗

1. Introduction & use cases

Django is a high-level Python web framework that includes almost everything a database-driven website needs: an ORM, migrations, an automatic admin panel, authentication, forms, templates, security protections (CSRF, XSS, SQL injection) and more.

A Django project contains settings and URLs; each feature is an app with models, views and templates. In production Django runs under a WSGI/ASGI server such as Gunicorn, behind Nginx which also serves static files.

Where it is used

  • Content sites, news portals and CMSs
  • E-commerce, booking and SaaS back-ends
  • REST APIs with Django REST Framework
  • Internal tools that need an admin panel quickly

2. Prerequisites

You needVersion / notes
PythonA supported 3.x release (3.11 or newer recommended) – check with python3 --version
pip + venvIncluded with Python
DatabaseSQLite for development; PostgreSQL or MySQL in production
BasicsPython, HTML and HTTP

3. Local setup

  1. 1Create a project folder and venv

    Everything happens inside the virtual environment.

    BASH
    mkdir mysite && cd mysite
    python3 -m venv .venv
    source .venv/bin/activate   # Windows: .venv\Scripts\activate
  2. 2Install Django

    Pin the version in requirements.txt.

    BASH
    pip install django
    pip freeze > requirements.txt
    python -m django --version
  3. 3Start a project

    The trailing dot creates the project in the current folder.

    BASH
    django-admin startproject config .
    python manage.py migrate
    python manage.py runserver

4. Create & run a project

  1. 1Create an app

    Apps hold one feature each. Create it with python manage.py startapp blog, then register it in INSTALLED_APPS.

    config/settings.py
    INSTALLED_APPS = [
        # ...
        "blog",
    ]
  2. 2Define a model

    Models map to database tables.

    blog/models.py
    from django.db import models
    
    class Post(models.Model):
        title = models.CharField(max_length=200)
        body = models.TextField()
        published = models.DateTimeField(auto_now_add=True)
    
        def __str__(self):
            return self.title
  3. 3Create the table and an admin user

    Make and apply migrations, register the model in the admin, then log in at /admin.

    BASH
    python manage.py makemigrations
    python manage.py migrate
    python manage.py createsuperuser
    
    # blog/admin.py
    from django.contrib import admin
    from .models import Post
    admin.site.register(Post)
  4. 4Add a view and URL

    A simple JSON view; templates work the same way with render().

    PYTHON
    # blog/views.py
    from django.http import JsonResponse
    from .models import Post
    
    def post_list(request):
        posts = list(Post.objects.values("id", "title")[:20])
        return JsonResponse({"posts": posts})
    
    # config/urls.py
    from django.contrib import admin
    from django.urls import path
    from blog.views import post_list
    
    urlpatterns = [
        path("admin/", admin.site.urls),
        path("api/posts/", post_list),
    ]
  5. 5Run the server

    Open http://127.0.0.1:8000/admin and /api/posts/.

    BASH
    python manage.py runserver

✅ When it works you should see output like Figure 1.

5. Development configuration

Environment variables

Never keep SECRET_KEY, DEBUG=True or database passwords in settings.py for production. Read them from environment variables (e.g. with django-environ or os.environ).

.env
# .env
DJANGO_SECRET_KEY=generate-a-long-random-value
DJANGO_DEBUG=False
DJANGO_ALLOWED_HOSTS=example.com,www.example.com
DATABASE_URL=postgres://django:pass@localhost:5432/mysite

# config/settings.py
import os
SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]
DEBUG = os.environ.get("DJANGO_DEBUG") == "True"
ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS", "").split(",")
STATIC_ROOT = BASE_DIR / "staticfiles"

Key dependencies

Package / toolUsed for
djangoFramework, ORM, admin, auth
gunicornProduction WSGI server
psycopg (psycopg[binary])PostgreSQL driver
django-environ / python-dotenvSettings from environment
djangorestframeworkREST APIs
whitenoise (optional)Serve static files from Django itself

Folder structure

project structure
mysite/
├── config/            # project: settings, urls, wsgi/asgi
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── blog/              # an app
│   ├── migrations/
│   ├── admin.py
│   ├── models.py
│   └── views.py
├── templates/
├── static/
├── manage.py
└── requirements.txt

Essential commands

CommandWhat it does
python manage.py runserverDevelopment server
python manage.py makemigrations / migrateCreate and apply DB changes
python manage.py createsuperuserAdmin login
python manage.py collectstaticGather static files for production
python manage.py check --deployProduction security checklist
python manage.py shellInteractive shell with your models

6. Production deployment

Server & hosting requirements

RequirementRecommendation
ServerUbuntu VPS, 1–2 GB RAM
App serverGunicorn (WSGI) or Uvicorn (ASGI)
DatabasePostgreSQL / MySQL (managed RDS is fine)
Web serverNginx for proxy + /static/ and /media/
Domain + SSLDNS + Let’s Encrypt

Deployment steps

  1. 1Prepare an Ubuntu server

    Create a VPS (AWS EC2, DigitalOcean, Hostinger VPS, Linode …) with Ubuntu 24.04 LTS, at least 1 vCPU and 1–2 GB RAM. Log in with SSH, update the system and create a non-root user for the app.

    BASH
    ssh root@YOUR_SERVER_IP
    apt update && apt upgrade -y
    adduser deploy
    usermod -aG sudo deploy
    # copy your SSH key to the new user, then log in as deploy
    rsync --archive --chown=deploy:deploy ~/.ssh /home/deploy
    exit
    ssh deploy@YOUR_SERVER_IP
  2. 2Install Python on the server

    Ubuntu 24.04 ships Python 3.12. Install venv support and create the app user’s folder.

    BASH
    sudo apt install -y python3 python3-venv python3-pip
    sudo mkdir -p /srv/app && sudo chown deploy:deploy /srv/app
  3. 3Install PostgreSQL and create the database

    Or use a managed database such as AWS RDS.

    BASH
    sudo apt install -y postgresql
    sudo -u postgres psql -c "CREATE USER django WITH PASSWORD 'strong-password';"
    sudo -u postgres psql -c "CREATE DATABASE mysite OWNER django;"
  4. 4Get the code and prepare Django

    Install requirements in a server venv, apply migrations and collect static files.

    BASH
    git clone https://github.com/you/mysite.git /srv/app && cd /srv/app
    python3 -m venv .venv
    .venv/bin/pip install -r requirements.txt gunicorn "psycopg[binary]"
    nano .env                           # production values
    set -a; . ./.env; set +a
    .venv/bin/python manage.py migrate
    .venv/bin/python manage.py collectstatic --noinput
    .venv/bin/python manage.py check --deploy
  5. 5Run it as a systemd service

    systemd starts the app on boot and restarts it on failure. Save the unit file, then enable it. Logs: journalctl -u django -f.

    /etc/systemd/system/django.service
    [Unit]
    Description=django
    After=network.target
    
    [Service]
    User=deploy
    WorkingDirectory=/srv/app
    EnvironmentFile=/srv/app/.env
    ExecStart=/srv/app/.venv/bin/gunicorn config.wsgi:application --bind 127.0.0.1:8000 --workers 3
    Restart=always
    RestartSec=5
    
    [Install]
    WantedBy=multi-user.target
  6. 6Start and enable the service

    Reload systemd, start the service now and on every boot, and check that it is active (running).

    BASH
    sudo systemctl daemon-reload
    sudo systemctl enable --now django
    sudo systemctl status django
    journalctl -u django -f
  7. 7Configure Nginx

    Serve static files directly and proxy everything else to Gunicorn.

    /etc/nginx/sites-available/example.com
    server {
        listen 80;
        server_name example.com www.example.com;
    
        location /static/ { alias /srv/app/staticfiles/; }
        location /media/  { alias /srv/app/media/; }
    
        location / {
            proxy_pass http://127.0.0.1:8000;
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
        }
    }
  8. 8Enable the site and reload Nginx

    Link the config into sites-enabled, test it and reload. nginx -t must say syntax is ok before you reload.

    BASH
    sudo apt install -y nginx
    sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
    sudo nginx -t
    sudo systemctl reload nginx
  9. 9Open only the ports you need

    Allow SSH, HTTP and HTTPS through the firewall. Application ports (3000, 8000 …) stay closed to the internet – Nginx forwards traffic to them.

    BASH
    sudo ufw allow OpenSSH
    sudo ufw allow 'Nginx Full'   # ports 80 and 443 (after installing Nginx)
    sudo ufw enable
    sudo ufw status
  10. 10Point your domain to the server

    In your domain registrar's DNS panel add an A record for @ (and www) with the server's public IP address. DNS changes usually appear within minutes but can take up to 24–48 hours. Check with dig or an online DNS checker.

    OUTPUT
    # Type  Name  Value              TTL
    # A     @     203.0.113.10       3600
    # A     www   203.0.113.10       3600
    dig +short example.com
  11. 11Add free HTTPS with Let’s Encrypt

    Certbot gets a free SSL certificate, adds it to the Nginx config and redirects HTTP to HTTPS. Certificates renew automatically (a systemd timer runs twice a day); test renewal once with --dry-run.

    BASH
    sudo apt install -y certbot python3-certbot-nginx
    sudo certbot --nginx -d example.com -d www.example.com
    sudo certbot renew --dry-run
  12. 12Tell Django it is behind HTTPS

    After SSL works, enable secure cookies and trust the proxy header.

    config/settings.py
    SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
    SESSION_COOKIE_SECURE = True
    CSRF_COOKIE_SECURE = True
    CSRF_TRUSTED_ORIGINS = ["https://example.com"]

🗺 The whole path from your code to the live site is drawn in the deployment diagram.

7. Images & screenshots

Illustrations drawn for this guide from the commands above. Product dashboards change often, so for screens such as cloud consoles follow the step text and the official documentation.

terminal$ python manage.py runserverWatching for file changes with StatReloaderPerforming system checks...System check identified no issues (0 silenced).Django version 5.x, using settings 'config.settings'Starting development server at http://127.0.0.1:8000/Quit the server with CONTROL-C.
Figure 1: terminal output of the sample Django project (section 4).
1Models + views2migrate +collectstatic3Gunicorn :8000(systemd)4Nginx + /static/5HTTPS site
Figure 2: production deployment flow (section 6).
mysite/├── config/ # project: settings, urls, wsgi/asgi│ ├── settings.py│ ├── urls.py│ └── wsgi.py├── blog/ # an app│ ├── migrations/│ ├── admin.py│ ├── models.py│ └── views.py├── templates/├── static/├── manage.py└── requirements.txt
Figure 3: project folder structure (section 5).

8. Common errors & solutions

DisallowedHost: Invalid HTTP_HOST header

Add your domain (and server IP if needed) to ALLOWED_HOSTS.

Static files (CSS) missing in production

With DEBUG=False Django does not serve static files. Set STATIC_ROOT, run collectstatic, and add the Nginx location /static/ alias (or use WhiteNoise).

CSRF verification failed on forms after enabling HTTPS

Add https://yourdomain to CSRF_TRUSTED_ORIGINS and set SECURE_PROXY_SSL_HEADER.

django.db.utils.OperationalError: no such table

Run python manage.py migrate (and makemigrations if you changed models).

502 Bad Gateway

Gunicorn is not running. Check journalctl -u django -n 50 for the Python traceback.

ModuleNotFoundError: No module named 'config'

Gunicorn runs from the wrong folder. Set WorkingDirectory to the folder that contains manage.py.

Best practices

  • Run manage.py check --deploy before every launch.
  • Keep DEBUG=False and secrets in environment variables.
  • Use PostgreSQL in production and back it up daily.
  • Serve user uploads from object storage (S3) for multi-server setups.
  • Put each feature in its own app and write tests with manage.py test or pytest-django.