Skip to main content

Django Heroku Deployment

Deploying your Django application to a production environment is a crucial step in making your web application available to users. Heroku provides one of the simplest paths to deployment, especially for beginners. In this guide, we'll walk through the process of deploying a Django application to Heroku step by step.

Introduction to Heroku

Heroku is a cloud Platform-as-a-Service (PaaS) that enables developers to build, run, and operate applications entirely in the cloud. It abstracts away many of the infrastructure concerns, allowing you to focus on your code rather than server configuration and maintenance.

Benefits of Heroku for Django deployment:

  • No server administration required
  • Simple scaling options
  • Built-in PostgreSQL database
  • Easy integration with other services
  • Free tier for testing and small projects

Prerequisites

Before we begin, make sure you have:

  1. A working Django application
  2. Git installed on your machine
  3. A Heroku account (sign up at heroku.com)
  4. Heroku CLI installed (download from devcenter.heroku.com/articles/heroku-cli)

Step 1: Prepare Your Django Project

First, we need to make some adjustments to our Django project to make it work well in Heroku's environment.

Install Required Packages

bash
pip install gunicorn dj-database-url psycopg2-binary whitenoise
  • gunicorn: A WSGI HTTP server for running Django in production
  • dj-database-url: Utility to configure Django database using environment variables
  • psycopg2-binary: PostgreSQL adapter for Python
  • whitenoise: For serving static files efficiently

Update Requirements File

Make sure these dependencies are in your requirements.txt file:

bash
pip freeze > requirements.txt

Create a Procfile

Create a file named Procfile (without any extension) in the root of your project:

text
web: gunicorn your_project_name.wsgi --log-file -

Replace your_project_name with the name of your Django project (the folder containing the settings.py file).

Configure Django Settings

Update your settings.py file to work with Heroku's environment. It's a good practice to separate development and production settings:

python
# settings.py

import os
import dj_database_url
from pathlib import Path

# Build paths inside the project
BASE_DIR = Path(__file__).resolve().parent.parent

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('SECRET_KEY', 'your-default-development-key')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.environ.get('DEBUG', 'True') == 'True'

ALLOWED_HOSTS = ['localhost', '127.0.0.1', '.herokuapp.com']

# Application definition
# ... (rest of your installed apps)

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware', # Add whitenoise middleware
# ... (rest of your middleware)
]

# Database configuration
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}

# Update database configuration from $DATABASE_URL environment variable
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)

# Static files (CSS, JavaScript, Images)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

# Extra places for collectstatic to find static files
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]

# Simplified static file serving with Whitenoise
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

# Default primary key field type
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

Create Static Directory

Ensure you have a static directory at the project root level:

bash
mkdir static

Step 2: Setup Git Repository

If your project isn't already in a Git repository, initialize one:

bash
git init

Create a .gitignore file to exclude unnecessary files:

text
# .gitignore
*.pyc
db.sqlite3
__pycache__/
*.py[cod]
*$py.class
.env
.venv
env/
venv/
ENV/
staticfiles/
.DS_Store

Commit your changes:

bash
git add .
git commit -m "Prepare for Heroku deployment"

Step 3: Create Heroku App

Log in to Heroku using the CLI:

bash
heroku login

Create a new Heroku application:

bash
heroku create your-app-name

Replace your-app-name with a unique name for your application. If you don't specify a name, Heroku will assign a random one.

Step 4: Configure Heroku Settings

Set Environment Variables

bash
heroku config:set SECRET_KEY="your-super-secret-key"
heroku config:set DEBUG="False"

Add PostgreSQL Database

bash
heroku addons:create heroku-postgresql:hobby-dev

This adds a free PostgreSQL database to your Heroku application.

Step 5: Deploy to Heroku

Push your code to Heroku:

bash
git push heroku main

If your branch is named master instead of main, use:

bash
git push heroku master

Step 6: Run Migrations and Create Superuser

Run migrations to set up your database schema:

bash
heroku run python manage.py migrate

Create a superuser for the admin interface:

bash
heroku run python manage.py createsuperuser

Step 7: Collect Static Files

bash
heroku run python manage.py collectstatic --noinput

Step 8: Open Your Application

bash
heroku open

This will open your deployed application in your default web browser.

Common Issues and Troubleshooting

1. Database Connection Issues

If you're experiencing database connection problems, check your database URL:

bash
heroku config:get DATABASE_URL

Ensure that dj_database_url.config() is properly configured in your settings.

2. Static Files Not Loading

If your static files aren't loading properly:

  • Make sure whitenoise is correctly installed and configured
  • Verify that STATIC_ROOT and STATICFILES_DIRS are properly set
  • Run collectstatic again
bash
heroku run python manage.py collectstatic --noinput --clear

3. Application Error or Crashes

Check your application logs:

bash
heroku logs --tail

Real-world Example: Deploying a Django Blog

Let's walk through a complete example of deploying a simple Django blog app to Heroku:

  1. Project structure:
blog_project/
├── blog/
│ ├── __init__.py
│ ├── admin.py
│ ├── apps.py
│ ├── models.py
│ ├── templates/
│ ├── tests.py
│ └── views.py
├── blog_project/
│ ├── __init__.py
│ ├── asgi.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── manage.py
├── Procfile
├── requirements.txt
└── static/
└── css/
└── style.css
  1. Create Procfile:
web: gunicorn blog_project.wsgi --log-file -
  1. Update requirements.txt:
Django==4.0.0
gunicorn==20.1.0
dj-database-url==0.5.0
psycopg2-binary==2.9.3
whitenoise==6.0.0
  1. Deploy:
bash
git add .
git commit -m "Ready for deployment"
heroku create django-blog-example-app
git push heroku main
heroku run python manage.py migrate
heroku run python manage.py createsuperuser
heroku open

Scaling Your Heroku Application

As your application grows, you might need to scale it:

bash
# To scale your web dynos
heroku ps:scale web=2

# To upgrade to a different dyno type
heroku ps:resize web=standard-2x

Maintaining Your Heroku Application

Regular Updates

Keep your dependencies updated:

bash
pip install --upgrade -r requirements.txt
pip freeze > requirements.txt
git commit -am "Update dependencies"
git push heroku main

Database Backups

Schedule regular database backups:

bash
heroku pg:backups schedule --at '02:00 America/New_York' DATABASE_URL

Download a backup:

bash
heroku pg:backups:download

Summary

In this guide, we've covered how to deploy a Django application to Heroku:

  1. Preparing your Django project with necessary configuration
  2. Setting up Git for version control
  3. Creating a Heroku app
  4. Configuring environment variables and add-ons
  5. Deploying your code
  6. Running migrations and collecting static files
  7. Troubleshooting common issues
  8. Maintaining and scaling your application

Deploying to Heroku provides a straightforward path to making your Django application available online with minimal server management overhead. As your application grows, you can easily scale resources to match your needs.

Additional Resources

Exercises

  1. Deploy a simple Django "Hello World" application to Heroku
  2. Add a custom domain to your Heroku app (Hint: Look up heroku domains:add)
  3. Set up automatic deployments from GitHub to Heroku
  4. Create a staging environment for your application using Heroku pipelines
  5. Implement HTTPS with Heroku's free SSL

Happy deploying!



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)