How to Deploy Django to Heroku: Step-by-Step Guide
To deploy a Django app to Heroku, create a
Procfile, add gunicorn and dj-database-url to your requirements.txt, configure settings.py for production, then push your code to Heroku using git push heroku main. Heroku will build and run your app automatically.Syntax
Deploying Django to Heroku involves these key files and commands:
Procfile: tells Heroku how to run your app.requirements.txt: lists Python packages Heroku installs.runtime.txt: specifies Python version.git push heroku main: deploys your code to Heroku.
Each part ensures Heroku knows how to build and start your Django app.
bash
web: gunicorn your_project_name.wsgi --log-file - # requirements.txt example Django>=4.2 gunicorn dj-database-url psycopg2-binary # runtime.txt example python-3.11.4
Example
This example shows a minimal setup to deploy a Django app named myproject to Heroku.
It includes the Procfile, requirements.txt, and a snippet from settings.py to configure the database.
plaintext
# Procfile web: gunicorn myproject.wsgi --log-file - # requirements.txt Django>=4.2 gunicorn dj-database-url psycopg2-binary # settings.py snippet import dj_database_url import os DATABASES = { 'default': dj_database_url.config(default='sqlite:///db.sqlite3') } # Allow all hosts for Heroku ALLOWED_HOSTS = ['*']
Output
Heroku builds the app, installs dependencies, and runs gunicorn to serve your Django app on the web.
Common Pitfalls
Common mistakes when deploying Django to Heroku include:
- Not creating a
Procfile, so Heroku doesn't know how to start the app. - Forgetting to add
gunicorntorequirements.txt, causing runtime errors. - Not configuring
ALLOWED_HOSTSto include Heroku's domain. - Missing database configuration with
dj-database-url, leading to connection errors. - Using SQLite in production, which is not supported well on Heroku.
Fix these by adding the missing files, packages, and proper settings.
plaintext
# Wrong Procfile (missing)
# No Procfile means Heroku can't start the app
# Right Procfile
web: gunicorn myproject.wsgi --log-file -Quick Reference
Summary tips for deploying Django to Heroku:
- Use
gunicornas the web server. - Create a
Procfilewithweb: gunicorn your_project_name.wsgi --log-file -. - List all dependencies in
requirements.txt. - Configure
DATABASESinsettings.pyusingdj-database-url. - Set
ALLOWED_HOSTSto include your Heroku app domain or use['*']for testing. - Use PostgreSQL add-on on Heroku instead of SQLite.
- Deploy with
git push heroku main.
Key Takeaways
Create a Procfile to tell Heroku how to run your Django app with gunicorn.
Add gunicorn and dj-database-url to requirements.txt for proper server and database support.
Configure your settings.py to use dj-database-url for Heroku's PostgreSQL database.
Set ALLOWED_HOSTS correctly to avoid host header errors on Heroku.
Deploy your app by pushing your git repository to Heroku with git push heroku main.