Deploying a Django app to Heroku

Note to self — before deploying a local Django app to Heroku I should do the following:

Install the wsgi HTTP server, gunicorn:

pip install gunicorn

Install package to help work with environment variables:

pip install python-dotenv

Install Python-PostgreSQL Database Adapter:

pip install psycopg2

Create requirements file:

pip freeze > requirements.txt

Configure to load environment variables and the database:

import dotenv
import dj_database_url

# this line is already in your
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# load environment variables from .env
dotenv_file = os.path.join(BASE_DIR, ".env")
if os.path.isfile(dotenv_file):

# load database from the DATABASE_URL environment variable
DATABASES['default'] = dj_database_url.config(conn_max_age=600)

Also delete the default database config:

    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),

Add a .env file to project base directory and add the database URL:


Make sure .env is added to .gitignore so it doesn’t get pushed to repo. My last .gitignore looked like:


Assuming there is already a heroku account run:

heroku login

locally to associate machine with heroku account.

On the heroku dashboard create a new app. Under the “Settings” tab and under “Buildpacks” add a new buildpack called “heroku/python”.

Under “Config Variables” add “DISABLE_COLLECTSTATIC” with a value of “1”.

To set-up the database go back to command line and enter:

heroku addons:create heroku-postgresql:hobby-dev -a YOUR_APP_NAME

This provisions a new postgres database and should add the url to the Config Variables. Run command:

heroku config -a YOUR_APP_NAME

DATABASE_URL should be added to Config Variables.

Now create a new file called Procfile in the base directory of project and add:

web: gunicorn YOURSITE.wsgi --log-level=info --log-file -

Where YOURSITE is specific to the project.

Add another file in base directory called runtime.txt and add the version of python you want to use:


To serve static assets I use the WhiteNoise project. To install:

pip install whitenoise
pip freeze > requirements.txt

Add it to the app by changing to include:

from django.core.wsgi import get_wsgi_application
from whitenoise.django import DjangoWhiteNoise

application = get_wsgi_application()
application = DjangoWhiteNoise(application)

Now that should be it! Commit the changes locally then run:

git push heroku master

It should display the progress of installation and eventually be up and running.


This was trying to put a bunch of stuff I read in the articles below into an order I’ve found works for me.

Leave a Reply

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