Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OperationalError could not connect to server

I put a Django app on Heroku recently. The home page looks fine, but when I try to go to a page that involves making a query (e.g. p = Photo.objects.get(title=title)), I get this error:

could not connect to server: Connection refused
    Is the server running on host "localhost" and accepting
    TCP/IP connections on port 5432?

In accordance with this answer, I did $ heroku pg:promote HEROKU_POSTGRESQL_GREEN_URL

Then in my settings.py:

DATABASES = {'default': dj_database_url.config(default=os.environ['DATABASE_URL'])}

Still got the same error, so I tried looking at the results of this (as this answer suggests):

$ heroku run python manage.py shell

>>> from django.conf import settings

>>> print settings.DATABASES['default']

{'TIME_ZONE': 'UTC', 'TEST_MIRROR': None, 'NAME': 'snorthway', 'OPTIONS': {}, 
'HOST': 'localhost', 'TEST_NAME': None, 'PASSWORD': '******', 'ENGINE': 
'django.db.backends.postgresql_psycopg2', 'PORT': '', 'USER': 'snorthway', 
'TEST_COLLATION': None, 'TEST_CHARSET': None}

At which point I realized I don't know what I should even be looking for in that. I still don't understand what the error means, so I am unsure how to go about debugging it.

like image 693
snorthway Avatar asked Jul 14 '13 02:07

snorthway


1 Answers

You have not configured your django database correctly in settings.py. It thinks your database is on localhost. Sounds like you have a heroku postgres database so your host should be something like:

df3-64-304-50-250.compute-1.amazonaws.com

Heroku exposes a special database URL through an environment variable called:

DATABASE_URL

There is a very cool python package here called dj_database_url: https://github.com/kennethreitz/dj-database-url it converts that environment variable to what django expects.

you can install it with:

$pip install dj-database-url

I use the following in my settings.py

import dj_database_url
DATABASES = {
    'default': dj_database_url.config()
}
like image 109
Rel Avatar answered Oct 31 '22 18:10

Rel