Learn Django Β· 13/13

Deployment: Going Live! 🌍

7 min read

Welcome to the deployment phase. Up until now, your Django application has lived comfortably on your local machine. Moving to production means putting your application on a server accessible to the public internet.

In this guide, we will transition your app from a local development environment to a secure, robust, and scalable production architecture.


1. Preparing for Production: DEBUG = False and ALLOWED_HOSTS πŸ›‘

Definition & Problem

DEBUG is a built-in Django setting (a boolean) that toggles the display of detailed error tracebacks.

The Problem: When DEBUG = True, any error in your app will render a massive yellow page revealing your source code, local file paths, database queries, and active environment variables. Leaving this on in production is a massive security riskβ€”it essentially hands over a map of your system vulnerabilities to anyone with a web browser.

ALLOWED_HOSTS is a list of strings representing the domain names or IP addresses that this Django site can serve.

The Problem: HTTP requests include a "Host" header indicating which domain the user is trying to reach. If an attacker fakes this header (Host Header Injection), they might trick Django into generating malicious password reset links pointing back to the attacker's phishing site instead of your actual domain.

The Solution

We turn DEBUG off and explicitly tell Django which exact domains it is allowed to answer.

python
# settings.py

# NEVER leave this True in production!
DEBUG = False

# Django will only respond to requests directed at these exact domains/IPs.
ALLOWED_HOSTS = ['www.yourdomain.com', 'yourdomain.com', '203.0.113.42']

Fun Fact: There have been real-world incidents where developers left DEBUG = True in production, accidentally leaking their AWS database credentials on a simple 404 page, leading to massive data breaches within hours. Always double-check this setting!


2. Hiding Secrets: Managing Environment Variables (python-dotenv) πŸ•΅οΈβ€β™‚οΈ

Definition & Problem

Environment variables are dynamic values stored at the operating system level rather than written directly into the application code.

The Problem: Your settings.py file contains highly sensitive information, such as your SECRET_KEY, database passwords, and third-party API keys. If you hardcode these into your code and push them to a version control system like GitHub, anyone with access to the repository can steal them.
(Imagine an automated malicious bot scraping GitHub, finding your AWS keys, and mining $50,000 worth of crypto on your account while you sleep. Yes, this happens constantly!)

The Solution

We extract all sensitive data out of the code base and store it in a .env file on the server. We then use a package called python-dotenv to load these values into Django's memory at runtime.

Implementation

  1. Install the package:

    bash
    pip install python-dotenv
  2. Create a .env file in the same directory as your manage.py. Put your secrets here:

    env
    # .env (Do NOT commit this file to Git)
    DJANGO_SECRET_KEY=django-insecure-super-secret-key-xyz
    DJANGO_DEBUG=False
  3. Protect the .env file:
    Immediately add .env to your .gitignore file so it never goes to GitHub.

    text
    # .gitignore
    .env
    __pycache__/
    db.sqlite3
  4. Update settings.py to read these variables:

    python
    # settings.py
    import os
    from dotenv import load_dotenv
    from pathlib import Path
    
    BASE_DIR = Path(__file__).resolve().parent.parent
    
    # Load environment variables from the .env file
    load_dotenv(os.path.join(BASE_DIR, '.env'))
    
    # Read the secrets
    SECRET_KEY = os.getenv('DJANGO_SECRET_KEY')
    
    # Convert the string 'False' from the .env file to a Python boolean
    DEBUG = os.getenv('DJANGO_DEBUG') == 'True'

3. Switching Databases: Moving from SQLite to PostgreSQL 🐘

Definition & Problem

SQLite is a C-language library that implements a lightweight, file-based SQL database engine.

The Problem: SQLite locks the entire database file whenever a write operation happens. If 100 users try to register an account at the exact same millisecond, 1 will succeed, and 99 will be blocked or crash. It is strictly built for local development and very small workloads.

PostgreSQL (often called Postgres) is a powerful, open-source object-relational database system with a dedicated client-server architecture.

The Problem it Solves: Postgres can handle thousands of concurrent read and write operations efficiently without locking the whole database, making it the industry standard for production Django apps.

The Solution

We will swap Django's database engine from SQLite to Postgres. To do this securely, we need psycopg (the PostgreSQL adapter for Python) and dj-database-url (an industry-standard utility that lets us configure the database using a single environment variable).

Implementation

  1. Install dependencies:
    (Note: Modern Django heavily recommends psycopg v3 over the older psycopg2 package).

    bash
    pip install psycopg[binary] dj-database-url
  2. Add your Database URL to .env:
    Instead of defining names, hosts, and ports individually, the industry standard is to use a single Connection URI.

    env
    # .env
    # Format: postgres://USER:PASSWORD@HOST:PORT/NAME
    DATABASE_URL=postgres://myuser:mypassword@localhost:5432/my_production_db
  3. Configure settings.py:

    python
    # settings.py
    import dj_database_url
    import os
    
    # Replace the default SQLite dictionary with this:
    DATABASES = {
        'default': dj_database_url.config(
            default=os.getenv('DATABASE_URL'),
            conn_max_age=600, # Connection pooling (keeps connections open for 10 mins)
            conn_health_checks=True,
        )
    }

(Under the hood: Django reads the DATABASE_URL string, automatically parses out the user, password, host, and engine, and translates it into the dictionary structure Django expects. conn_max_age tells Django not to aggressively close the database connection after every single request, drastically improving performance under load.)


4. Serving The App: WSGI, Gunicorn, and Web Servers (Nginx) 🍽️

Definition & Problem

The command python manage.py runserver starts Django's built-in development server.

The Problem: This development server is single-threaded. It processes exactly one request at a time. If a user with a slow internet connection is uploading a 10MB profile picture, every other user trying to view your website has to wait in line until that upload finishes. Additionally, it has never been security-audited to face raw, public internet traffic.

WSGI (Web Server Gateway Interface) is a specification that standardizes how web servers communicate with Python web applications.
Gunicorn ("Green Unicorn") is a Python WSGI HTTP Server. It creates multiple "workers" (copies of your app) so multiple requests can be handled concurrently.
Nginx is a high-performance web server and reverse proxy. It handles raw internet traffic, enforces HTTPS security, and serves static files directly.

How They Work Together (The Restaurant Scenario)

Imagine you are running a high-end restaurant with hundreds of customers.

  • Nginx is the Host/Maitre D'. They stand at the front door. They check reservations (security), hand out menus instantly without bothering the kitchen (serving static CSS/JS files), and organize the crowd.
  • Gunicorn is the Kitchen Manager. They take the complex food orders from the Host and assign them to available cooks.
  • Django (WSGI) is the Cook. They take the order, fetch the raw ingredients from the fridge (Database), cook the meal (process business logic), plate it up (HTML/JSON), and hand it back up the chain to the customer.

If you use runserver in production, you just have one cook who is also trying to be the host, take orders, and wash the dishes. It simply doesn't scale.

Implementation

  1. Install Gunicorn:

    bash
    pip install gunicorn
  2. Run your app with Gunicorn:
    Instead of runserver, you tell Gunicorn to look inside your project folder for the wsgi.py file.

    bash
    gunicorn myproject.wsgi:application --workers 3 --bind 0.0.0.0:8000

    How many workers? The industry standard formula for Gunicorn workers is (2 * CPU cores) + 1. If your server has 2 CPU cores, you run 5 workers. This ensures that if some workers are busy waiting for a database response, others can still immediately accept new incoming web requests.

  3. The Nginx Reverse Proxy (Brief Look):
    In production, you install Nginx on your Linux server and configure it to intercept port 80 (HTTP) and 443 (HTTPS). It fulfills static file requests instantly, and passes dynamic Python logic to Gunicorn running on port 8000.

    Example standard Nginx configuration block (usually placed in /etc/nginx/sites-available/myproject):

    nginx
    server {
        listen 80;
        server_name yourdomain.com www.yourdomain.com;
    
        # 1. Host gives out the menus (Static Files) instantly
        location /static/ {
            alias /path/to/your/project/staticfiles/;
        }
    
        # 2. Host passes complex orders to the Kitchen Manager (Gunicorn)
        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;
        }
    }

    Once Nginx is running, it handles the public web traffic, securely hiding your internal Gunicorn/Django processes, and giving you a fully robust, enterprise-ready deployment!


References & Extra Reading πŸ“š

Challenge

You are tasked with preparing a Django project for production deployment. Modify the provided settings.py file to implement critical security and configuration changes based on industry best practices.

Your goal is to refactor the settings from a development-focused setup to one that is secure, scalable, and ready for a live server.

Your Tasks:

  1. Import the necessary modules: os for environment variables and dj_database_url for database configuration.
  2. Securely manage the SECRET_KEY by retrieving its value from an environment variable named SECRET_KEY.
  3. Disable DEBUG mode to prevent exposing sensitive information in a production environment.
  4. Configure ALLOWED_HOSTS to permit requests specifically from "yourdomain.com" and "www.yourdomain.com".
  5. Replace the default SQLite database configuration with a production-ready PostgreSQL setup. The entire database connection should be configured using dj_database_url to parse a connection string from an environment variable named DATABASE_URL.

Expected result

The modified settings.py file should correctly reflect a production-ready configuration. The submitted code must include:

  • import os and import dj_database_url statements at the top of the file.
  • The SECRET_KEY assigned a value from os.getenv('SECRET_KEY').
  • The DEBUG variable set to False.
  • The ALLOWED_HOSTS list containing two strings: 'yourdomain.com' and 'www.yourdomain.com'.
  • The DATABASES dictionary completely replaced with a new configuration that calls dj_database_url.config(default=os.getenv('DATABASE_URL')) to set up the 'default' database connection.
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.