Deploying Django on Heroku

Introduction

Deploying a Django application to production can often feel like a complex process involving server configuration, database setup, and managing static files. However, Heroku provides a platform-as-a-service (PaaS) that simplifies deployment dramatically.

With Heroku, you don’t need to worry about infrastructure details such as provisioning servers, configuring Nginx, or maintaining operating systems. Instead, you can focus on your application code, while Heroku handles scalability, networking, and system management for you.

In this comprehensive guide, we will walk through every step required to deploy your Django project on Heroku — from installation and configuration to database setup and debugging.

What Is Heroku?

Heroku is a cloud-based platform that enables developers to deploy, manage, and scale web applications easily. It supports multiple programming languages, including Python, Node.js, Ruby, Java, and PHP.

When you deploy a Django project on Heroku, it:

  • Automatically manages your server environment.
  • Provides an easy integration with PostgreSQL databases.
  • Handles application scaling.
  • Supports continuous deployment through Git.
  • Offers environment variables for configuration.

Heroku is ideal for beginners and small to medium-sized projects because it allows you to get your Django app online with minimal effort.


Step 1: Preparing Your Django Project

Before deployment, make sure your Django project is production-ready.

Check Your Requirements

Create a requirements.txt file that includes all dependencies your Django app needs to run. You can generate it automatically with the command:

pip freeze > requirements.txt

Make sure that gunicorn, whitenoise, and psycopg2-binary are included since Heroku needs them for deployment and database connections.

Example:

Django>=5.0,<6.0
gunicorn
whitenoise
psycopg2-binary
dj-database-url
python-decouple

Step 2: Install the Heroku CLI

The Heroku Command Line Interface (CLI) allows you to interact with your Heroku account directly from your terminal. You can push code, scale applications, and run commands on your app remotely.

Installation

To install the Heroku CLI, use the following command (for macOS and Linux):

curl https://cli-assets.heroku.com/install.sh | sh

For Windows users, download and install from the official Heroku website.

Once installed, verify the installation with:

heroku --version

If the CLI is correctly installed, you should see a version number printed in your terminal.


Step 3: Log in to Heroku

Run the command below to log in to your Heroku account:

heroku login

This will open a browser window prompting you to log in. Once you authenticate, you’ll be connected to your Heroku account in the terminal.

If you’re using Git Bash or WSL, you can use:

heroku login -i

This allows you to log in directly through the command line.


Step 4: Install Required Python Packages

Heroku requires gunicorn as a production server, whitenoise for serving static files, and psycopg2-binary to connect to the PostgreSQL database. Install them with pip:

pip install gunicorn whitenoise psycopg2-binary dj-database-url

These packages play specific roles:

  • Gunicorn: Runs your Django app as a WSGI application server.
  • Whitenoise: Allows Django to serve static files efficiently.
  • Psycopg2-binary: Enables PostgreSQL database connectivity.
  • Dj-database-url: Simplifies reading database configuration from environment variables.

Step 5: Create a Procfile

The Procfile tells Heroku how to run your application.

Create a file named Procfile (without any file extension) in your project’s root directory.

Add the following line:

web: gunicorn projectname.wsgi

Replace projectname with your actual Django project name (the folder that contains wsgi.py).

The web: command specifies that Gunicorn should start your application’s web process when Heroku launches your app.


Step 6: Configure Whitenoise for Static Files

Heroku does not automatically serve static files, so you must configure Django to do it.

Open your Django project’s settings.py and add Whitenoise to the middleware section:

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
...
]

Define Static File Paths

At the bottom of settings.py, define your static and media settings:

STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'

Then, collect all static files into this folder with:

python manage.py collectstatic

Whitenoise will now compress and serve static files directly from your Django app without needing an external web server.


Step 7: Configure the Database

By default, Heroku uses PostgreSQL as its database engine. You can connect to it easily using the dj-database-url library.

Add this to your settings.py:

import dj_database_url
from decouple import config

DATABASES = {
'default': dj_database_url.config(
    default=config('DATABASE_URL')
)
}

This configuration reads your database connection string from Heroku’s environment variable named DATABASE_URL.


Step 8: Disable Debug Mode and Set Allowed Hosts

For production, you must set:

DEBUG = False
ALLOWED_HOSTS = ['yourappname.herokuapp.com']

Replace yourappname with your actual Heroku app name.

If you want to handle multiple environments, you can add logic to load allowed hosts dynamically using environment variables.


Step 9: Initialize Git and Connect to Heroku

Your project must be under Git version control for Heroku deployment.

If you haven’t initialized Git yet, do so with:

git init
git add .
git commit -m "Initial commit for Heroku deployment"

Now create a new Heroku app:

heroku create yourappname

If you omit yourappname, Heroku will generate a random one for you.

You’ll see a URL like:

https://yourappname.herokuapp.com/

Step 10: Push Code to Heroku

Once your app is created, you can deploy it using Git.

Run:

git push heroku main

If your branch is master, use:

git push heroku master

Heroku will automatically detect that this is a Python app, install dependencies from requirements.txt, and run the Procfile command.

During deployment, you will see logs indicating build progress. If everything goes well, you’ll receive a success message showing your app is live.


Step 11: Apply Database Migrations

After deployment, your app is live, but the database still needs migrations. Run:

heroku run python manage.py migrate

This executes Django’s migration commands directly on Heroku’s server.

You can also create a superuser for the admin interface:

heroku run python manage.py createsuperuser

Follow the prompts to set your username, email, and password.


Step 12: Managing Environment Variables

Environment variables in Heroku are managed using config vars.

You can view them with:

heroku config

To add new variables, use:

heroku config:set DEBUG=False SECRET_KEY='your_secret_key'

For example, if your application uses an external API key, store it securely as a config variable instead of hardcoding it in your code.


Step 13: Connecting to the Database Locally

If you want to access your Heroku PostgreSQL database locally, you can use the following command:

heroku pg:psql

This opens an interactive PostgreSQL shell connected to your Heroku app’s database.

You can inspect tables, run queries, and verify your data directly.


Step 14: Testing the Deployment

Once your application is deployed, open it in your browser:

heroku open

This command automatically launches your Heroku app’s URL.

If everything was configured correctly, your Django homepage should appear live on the internet.


Step 15: Debugging Common Deployment Issues

While deploying Django to Heroku is straightforward, you might face some issues. Let’s look at common ones and how to fix them.

1. Application Error (500)

This usually indicates a database or configuration issue. Run the logs command:

heroku logs --tail

Check for detailed error messages. Common causes include incorrect ALLOWED_HOSTS or missing environment variables.

2. Static Files Not Found

Ensure you’ve added Whitenoise and executed:

python manage.py collectstatic

3. Slug Compilation Failed

This error means your dependencies may have failed to install. Verify your requirements.txt for accuracy.

4. H10 Error

This indicates that the web process crashed. Check if your Procfile syntax and gunicorn configuration are correct.


Step 16: Scaling and Managing Dynos

Heroku runs applications using dynos — lightweight containers that run your code.

By default, a free plan provides one web dyno. You can scale the number of dynos using:

heroku ps:scale web=1

To stop dynos:

heroku ps:stop web

To view running dynos:

heroku ps

For production, you can upgrade your dyno type to ensure better performance.


Step 17: Using the Heroku Dashboard

The Heroku dashboard provides a visual interface for managing your application.

From the dashboard, you can:

  • View logs and metrics.
  • Configure environment variables.
  • Access add-ons like Heroku Postgres, Redis, and SendGrid.
  • Enable automatic deployment from GitHub.

Visit:
https://dashboard.heroku.com

Select your application to manage settings directly from your browser.


Step 18: Adding Add-ons

Heroku supports various add-ons that extend your application’s functionality.

Some popular add-ons for Django apps include:

  • Heroku Postgres – Database management.
  • Redis – Caching and message queuing.
  • SendGrid – Email sending.
  • Sentry – Error tracking.

You can add an add-on with:

heroku addons:create heroku-redis:hobby-dev

Step 19: Setting Up Automatic Deployments

Heroku allows you to set up automatic deployments from GitHub.

Steps:

  1. Go to your Heroku dashboard.
  2. Select your app.
  3. Navigate to the Deploy tab.
  4. Connect your GitHub repository.
  5. Enable Automatic Deploys.

Now, each time you push to your GitHub branch, Heroku will automatically rebuild and deploy your app.


Step 20: Configuring Custom Domains

You can add a custom domain to your Heroku app, such as www.yourdomain.com.

Add your domain with:

heroku domains:add www.yourdomain.com

Heroku will return a DNS target. Add this target to your domain registrar’s DNS settings.

To view domains configured for your app:

heroku domains

Once DNS propagation completes, your app will be accessible from your custom domain.


Step 21: Setting Up HTTPS with Automatic SSL

Heroku provides automatic SSL certificates for custom domains through Let’s Encrypt.

Enable SSL using:

heroku certs:auto:enable

You can check the status of your certificate with:

heroku certs:auto

Once SSL is active, your site will automatically redirect all traffic to HTTPS, improving security.


Step 22: Monitoring Logs and Application Health

To monitor logs in real time, use:

heroku logs --tail

This displays live output of your application’s activity, including errors and requests.

You can also view performance metrics on the Heroku dashboard, such as:

  • Response time
  • Memory usage
  • Throughput

These metrics help optimize your app’s performance and detect issues early.


Step 23: Upgrading and Managing Add-ons

Heroku add-ons often come in free and paid tiers. To upgrade an add-on (like your database):

heroku addons:upgrade heroku-postgresql:standard-0

To remove an add-on:

heroku addons:destroy heroku-redis

Always verify billing before upgrading any paid add-ons.


Step 24: Maintaining and Updating Your Application

Once your Django app is live, you’ll need to maintain it by pushing updates, managing migrations, and monitoring performance.

To deploy updates:

git add .
git commit -m "Updated feature"
git push heroku main

Heroku will automatically rebuild your environment with the latest changes.

You can also run management commands anytime using:

heroku run python manage.py command_name

Step 25: Advantages of Deploying on Heroku

Heroku offers several advantages that make it one of the easiest and most powerful platforms for deploying Django apps:

  1. Simplified Deployment – Just push your code with Git.
  2. Scalability – Scale your app with a single command.
  3. Managed Databases – Fully hosted PostgreSQL instances.
  4. Environment Management – Secure config vars and easy integration.
  5. Automatic SSL – Built-in HTTPS support.
  6. Third-Party Add-ons – Integration with caching, mail, and analytics services.
  7. Developer Friendly – Great for both beginners and experienced developers.

Step 26: Limitations of Heroku’s Free Tier

While Heroku’s free plan is excellent for testing and learning, it has limitations:

  • Apps sleep after 30 minutes of inactivity.
  • Limited number of monthly dyno hours.
  • Slower cold starts.
  • No persistent file storage.

For professional or production-grade projects, consider upgrading to a paid plan to avoid downtime and performance issues.


Step 27: Best Practices for Django on Heroku

Follow these tips for a smooth production experience:

  • Always set DEBUG = False in production.
  • Keep all credentials in Heroku config vars.
  • Use Whitenoise to serve static files efficiently.
  • Monitor logs regularly with heroku logs --tail.
  • Use add-ons for caching and error tracking.
  • Regularly back up your PostgreSQL database.
  • Use python-decouple to manage environment settings safely.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *