I'm now learning Django and am following the Django book step by step.
When I proceeded to chapter 5 to connect my Django project to my database, I can't get it to connect. I get the error:
FATAL: password authentication failed for user "postgres"
Here's the code:
settings.py
configuration:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'postgis', # Or path to database file if using sqlite3.
'USER': 'postgres', # Not used with sqlite3.
'PASSWORD': 'XXXXXXX', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '8904', # Set to empty string for default. Not used with sqlite3.
}
}
But when I'm testing the connection and settings in Python shell with these codes:
from django.db import connection
cursor=connection.cursor()
the shell replies with the error:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "E:\Python27\lib\site-packages\django-1.4.1- py2.7.egg\django\db\backends\__init__.py", line 306, in cursor
cursor = self.make_debug_cursor(self._cursor())
File "E:\Python27\lib\site-packages\django-1.4.1-py2.7.egg\django\db\backends\
postgresql_psycopg2\base.py", line 177, in _cursor
self.connection = Database.connect(**conn_params)
File "E:\Python27\lib\site-packages\psycopg2\__init__.py", line 179, in connect
connection_factory=connection_factory, async=async)
OperationalError: FATAL: password authentication failed for user "postgres"
then I reinstalled the PostgreSQL and pycopg2 packages. I started pgAdminIII to run the server and connected to database, then I run the same code in python shell, but the problem still exists.
Need Help!
At a guess, you're using the wrong password, or your pg_hba.conf
isn't correctly configured.
Can you connect using psql
with the desired credentials? Try:
psql -U postgres -W -p 8904 postgis
If not, check pg_hba.conf
to see the postgres
user is using ident
or md5
security. If you want to use password connections it needs to be md5
. If you change the setting, use pg_ctl reload
or just restart PostgreSQL to make the change take effect.
You can find pg_hba.conf
by connecting to your DB with psql
and running SHOW hba_file;
. Eg:
sudo -u postgres psql -c 'SHOW hba_file;'
Note that you should never user a PostgreSQL superuser for an application connection anyway. Create a new user and have Django use that user on a new database. For example, to create a user named django
and a database named django_db
that's owned by the django
user:
sudo -u postgres createuser -SDR -P django
sudo -u postgres createdb -O django_db django;
The -SDR
makes the default explicit, that the django
user should not be a superuser and should not have CREATEDB
or CREATEUSER
rights.