Separating local and Heroku database settings for Django

For when Heroku settings break your local build

July 29, 2015

I'm currently building a small Django app, and I wanted to deploy it to Heroku. To do this, Heroku asks you to implement some specific database settings at the bottom of your settings.py file:

import dj_database_url
DATABASES['default'] =  dj_database_url.config()

The problem with this was that although these settings worked when the project was deployed to Heroku, they broke my local build with the following error:

raise ImproperlyConfigured("settings.DATABASES is improperly configured. "
django.core.exceptions.ImproperlyConfigured: settings.DATABASES 
is improperly configured. 
Please supply the ENGINE value. Check settings documentation for more details.

The reason I was getting this on my local build is that dj_database expects an environment variable, "DATABASE_URL", to be present on the local system, like it is when running on Heroku.

The simple solution I came up with was to add a an IF statement in to settings.py to detect whether or not the environment variable was present:

env = os.environ.copy()
db_url = env.get('DATABASE_URL', False)

if db_url != False:
    import dj_database_url
    DATABASES['default'] =  dj_database_url.config()

You can't just say 'if env['DATABASE_URL']' as this raises a KeyError. So instead I've used the 'get' method to either assign the value of the environment variable if it exists, or the default, 'False', if it doesn't. And voilĂ ! My app now runs on both my local machine and Heroku.

database Heroku django