Q:

django - error adding database to heroku

I am struggling to deploy my app on heroku. Mainly due to database configuration.
This is the bottom of the settings.py file, 
import dj_database_url

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

try:
    from .local_settings import *
except ImportError:
    pass

This is my local_settings.py file, 
import os
BASE_DIR = os.path.dirname(os.path.dirname(file))
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'test',
        'USER': 'test',
        'PASSWORD': 'postgres',
        'HOST': 'localhost',
        'PORT': 5432,
    }  
}

I can run heroku local web successfuly. 
But when I run , heroku run python manage.py migrate, it gives me error, 
django.db.utils.OperationalError: could not connect to server: Connection refused
    Is the server running on host "localhost" (127.0.0.1) and accepting
    TCP/IP connections on port 5432?

When I run, heroku run python manage.py shell,
And then run 
>>> import dj_database_url
>>> dj_database_url.config()

I get the dictionary giving me the full information about the database.
Where is the issue ?

A:

Try importing the settings from local_settings.py first, then change the DATABASES setting,
import dj_database_url
try:
    from .local_settings import *
except ImportError:
    pass

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

You have defined a DATABASES variable in the file, but when you are importing the local_settings.py, your DATABASES configuration is being overridden by the development values. You should do the import first and then change the DATABASES option.
Personally, I'd suggest that you should keep a base_settings.py to contain every settings other than databases, then import the same into the heroku_settings.py, rather than importing the whole local_settings.
Keeping a base_settings, development_settings, heroku_settings(or production_settings) would make it easier to handle the deployment.

