Search code examples
djangodatabaseheroku

Django apps on Heroku: how to access a shared database


On Heroku, it is possible to share a database among apps using the following command:

$ heroku addons:attach <databaseName> -a <appName>

where <databaseName> is the shared database (belonging to another app) and it is attached to the app <appName> (a Django application).

I googled around for a long time but couldn't find anything describing how to access the attached database in the app. Do I need to add or modify something to Django's settings.py and what? How do I access the attached database in Django's views.py?

The following is the setting for Heroku databases and database accessing is just via ORM.

# Parse database configuration from $DATABASE_URL
import dj_database_url
DATABASES = {'default':dj_database_url.config()}
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

Thanks.


Solution

  • Heroku always supplies configuration details as environment variables. When you do addons:attach it will print the name of the variable it has created for your attached add-on; alternatively you can specify it with the --as flag.

    heroku addons:attach <databaseName> -a <appName> --as MY_ATTACHED_DB_URL
    

    Now you can pass that variable name to the config call:

    DATABASES = {
        'default':dj_database_url.config(),
        'course': dj_database_url.config('MY_ATTACHED_DB_URL')
    }