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:
- A working Django application
- Git installed on your machine
- A Heroku account (sign up at heroku.com)
- 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
pip install gunicorn dj-database-url psycopg2-binary whitenoise
gunicorn
: A WSGI HTTP server for running Django in productiondj-database-url
: Utility to configure Django database using environment variablespsycopg2-binary
: PostgreSQL adapter for Pythonwhitenoise
: For serving static files efficiently
Update Requirements File
Make sure these dependencies are in your requirements.txt
file:
pip freeze > requirements.txt
Create a Procfile
Create a file named Procfile
(without any extension) in the root of your project:
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:
# 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:
mkdir static
Step 2: Setup Git Repository
If your project isn't already in a Git repository, initialize one:
git init
Create a .gitignore
file to exclude unnecessary files:
# .gitignore
*.pyc
db.sqlite3
__pycache__/
*.py[cod]
*$py.class
.env
.venv
env/
venv/
ENV/
staticfiles/
.DS_Store
Commit your changes:
git add .
git commit -m "Prepare for Heroku deployment"
Step 3: Create Heroku App
Log in to Heroku using the CLI:
heroku login
Create a new Heroku application:
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
heroku config:set SECRET_KEY="your-super-secret-key"
heroku config:set DEBUG="False"
Add PostgreSQL Database
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:
git push heroku main
If your branch is named master
instead of main
, use:
git push heroku master
Step 6: Run Migrations and Create Superuser
Run migrations to set up your database schema:
heroku run python manage.py migrate
Create a superuser for the admin interface:
heroku run python manage.py createsuperuser
Step 7: Collect Static Files
heroku run python manage.py collectstatic --noinput
Step 8: Open Your Application
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:
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
andSTATICFILES_DIRS
are properly set - Run
collectstatic
again
heroku run python manage.py collectstatic --noinput --clear
3. Application Error or Crashes
Check your application logs:
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:
- 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
- Create Procfile:
web: gunicorn blog_project.wsgi --log-file -
- 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
- Deploy:
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:
# 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:
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:
heroku pg:backups schedule --at '02:00 America/New_York' DATABASE_URL
Download a backup:
heroku pg:backups:download
Summary
In this guide, we've covered how to deploy a Django application to Heroku:
- Preparing your Django project with necessary configuration
- Setting up Git for version control
- Creating a Heroku app
- Configuring environment variables and add-ons
- Deploying your code
- Running migrations and collecting static files
- Troubleshooting common issues
- 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
- Official Heroku Django Deployment Guide
- Django on Heroku: Best Practices
- Configuring Django Apps for Heroku
- Heroku CLI Commands
Exercises
- Deploy a simple Django "Hello World" application to Heroku
- Add a custom domain to your Heroku app (Hint: Look up
heroku domains:add
) - Set up automatic deployments from GitHub to Heroku
- Create a staging environment for your application using Heroku pipelines
- 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! :)