Deploying a Django Web Application on Heroku (2025)
- Sign Up for Heroku:
Create an account at Heroku Signup.
- Install Git:
Download and install Git from the official website.
- Install the Heroku CLI:
Follow the instructions on the Heroku CLI documentation to install the Command Line Interface.
- Prepare Your Django Project:
-
Open your terminal and navigate to your project directory:
cd /path/to/your/project
-
Ensure your virtual environment is activated and install the necessary packages:
pip install gunicorn psycopg2-binary
Note:
psycopg2-binary
is required for PostgreSQL database support. -
Freeze your dependencies into a
requirements.txt
file:pip freeze > requirements.txt
-
- Configure
settings.py
:-
Import necessary modules at the top:
import os from pathlib import Path import dj_database_url
-
Set the
ALLOWED_HOSTS
to include your Heroku app's domain:ALLOWED_HOSTS = ['your-app-name.herokuapp.com']
-
Configure the database settings to use Heroku's PostgreSQL:
DATABASES = { 'default': dj_database_url.parse(os.environ.get('DATABASE_URL')) }
-
Configure static files settings:
STATIC_URL = '/static/' STATIC_ROOT = Path(BASE_DIR) / 'staticfiles'
-
Set the secret key and debug mode using environment variables:
SECRET_KEY = os.environ.get('SECRET_KEY', 'your-default-secret-key') DEBUG = os.environ.get('DEBUG', 'False') == 'True'
-
- Create a
Procfile
:In your project's root directory, create a file named
Procfile
(without any extension) and add the following line:web: gunicorn your_project_name.wsgi
Replace
your_project_name
with the name of your Django project directory. - Initialize a Git Repository:
-
Initialize the repository:
git init
-
Add all files:
git add .
-
Commit the changes:
git commit -m "Initial commit"
-
- Deploy to Heroku:
-
Create a new Heroku app:
heroku create your-app-name
Replace
your-app-name
with your desired app name. -
Set environment variables:
heroku config:set SECRET_KEY='your-secret-key' heroku config:set DEBUG='False'
-
Push your code to Heroku:
git push heroku master
-
Run database migrations on Heroku:
heroku run python manage.py migrate
-
Create a superuser for the admin interface:
heroku run python manage.py createsuperuser
-
Open your application in the browser:
heroku open
-
For a comprehensive guide, refer to the official Heroku documentation on Configuring Django Apps for Heroku.
Notes:
- The
django-heroku
package is no longer recommended. Instead, configure your settings manually as outlined above. - Ensure that your
SECRET_KEY
and other sensitive settings are managed securely using environment variables. - Regularly update your dependencies and configurations to align with the latest best practices and security recommendations.
For a visual walkthrough, you might find this video helpful:
Comments
You must be logged in to post a comment.
No comments yet. Be the first to comment!