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 need | Version / notes |
|---|---|
| Python | A supported 3.x release (3.11 or newer recommended) – check with python3 --version |
| pip + venv | Included with Python |
| Database | SQLite for development; PostgreSQL or MySQL in production |
| Basics | Python, HTML and HTTP |
3. Local setup
1Create a project folder and venv
Everything happens inside the virtual environment.
BASHmkdir mysite && cd mysite python3 -m venv .venv source .venv/bin/activate # Windows: .venv\Scripts\activate2Install Django
Pin the version in requirements.txt.
BASHpip install django pip freeze > requirements.txt python -m django --version3Start a project
The trailing dot creates the project in the current folder.
BASHdjango-admin startproject config . python manage.py migrate python manage.py runserver
4. Create & run a project
1Create an app
Apps hold one feature each. Create it with
python manage.py startapp blog, then register it inINSTALLED_APPS.config/settings.pyINSTALLED_APPS = [ # ... "blog", ]2Define a model
Models map to database tables.
blog/models.pyfrom 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.title3Create the table and an admin user
Make and apply migrations, register the model in the admin, then log in at
/admin.BASHpython 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)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), ]5Run the server
Open http://127.0.0.1:8000/admin and /api/posts/.
BASHpython 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
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 / tool | Used for |
|---|---|
django | Framework, ORM, admin, auth |
gunicorn | Production WSGI server |
psycopg (psycopg[binary]) | PostgreSQL driver |
django-environ / python-dotenv | Settings from environment |
djangorestframework | REST APIs |
whitenoise (optional) | Serve static files from Django itself |
Folder 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.txtEssential commands
| Command | What it does |
|---|---|
python manage.py runserver | Development server |
python manage.py makemigrations / migrate | Create and apply DB changes |
python manage.py createsuperuser | Admin login |
python manage.py collectstatic | Gather static files for production |
python manage.py check --deploy | Production security checklist |
python manage.py shell | Interactive shell with your models |
6. Production deployment
Server & hosting requirements
| Requirement | Recommendation |
|---|---|
| Server | Ubuntu VPS, 1–2 GB RAM |
| App server | Gunicorn (WSGI) or Uvicorn (ASGI) |
| Database | PostgreSQL / MySQL (managed RDS is fine) |
| Web server | Nginx for proxy + /static/ and /media/ |
| Domain + SSL | DNS + Let’s Encrypt |
Deployment steps
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.
BASHssh 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_IP2Install Python on the server
Ubuntu 24.04 ships Python 3.12. Install venv support and create the app user’s folder.
BASHsudo apt install -y python3 python3-venv python3-pip sudo mkdir -p /srv/app && sudo chown deploy:deploy /srv/app3Install PostgreSQL and create the database
Or use a managed database such as AWS RDS.
BASHsudo 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;"4Get the code and prepare Django
Install requirements in a server venv, apply migrations and collect static files.
BASHgit 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 --deploy5Run 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.target6Start and enable the service
Reload systemd, start the service now and on every boot, and check that it is active (running).
BASHsudo systemctl daemon-reload sudo systemctl enable --now django sudo systemctl status django journalctl -u django -f7Configure Nginx
Serve static files directly and proxy everything else to Gunicorn.
/etc/nginx/sites-available/example.comserver { 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; } }8Enable the site and reload Nginx
Link the config into
sites-enabled, test it and reload.nginx -tmust say syntax is ok before you reload.BASHsudo apt install -y nginx sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/ sudo nginx -t sudo systemctl reload nginx9Open 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.
BASHsudo ufw allow OpenSSH sudo ufw allow 'Nginx Full' # ports 80 and 443 (after installing Nginx) sudo ufw enable sudo ufw status10Point your domain to the server
In your domain registrar's DNS panel add an A record for
@(andwww) with the server's public IP address. DNS changes usually appear within minutes but can take up to 24–48 hours. Check withdigor 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.com11Add 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.BASHsudo apt install -y certbot python3-certbot-nginx sudo certbot --nginx -d example.com -d www.example.com sudo certbot renew --dry-run12Tell Django it is behind HTTPS
After SSL works, enable secure cookies and trust the proxy header.
config/settings.pySECURE_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.
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 --deploybefore every launch. - Keep
DEBUG=Falseand 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 testor pytest-django.