Django connection to PostgreSQL: "Peer authentication failed" Django connection to PostgreSQL: "Peer authentication failed" django django

Django connection to PostgreSQL: "Peer authentication failed"


I took a peek at the exception, noticed it had to do with my connection settings. Went back to settings.py, and saw I did not have a Host setup. Add localhost and voila.

My settings.py did not have a HOST for MySQL database, but I needed to add one for PostgreSQL to work.

In my case, I added localhost to the HOST setting and it worked.

Here is the DATABASES section from my settings.py.

DATABASES = {     'default': {         'ENGINE': 'django.db.backends.postgresql_psycopg2',        'NAME': '<MYDATABASE>',         'USER': '<MYUSER>',         'PASSWORD': '<MYPASSWORD>',         'HOST': 'localhost', # the missing piece of the puzzle         'PORT': '', # optional, I don't need this since I'm using the standard port    } }


That is probably because your script is running under some other user than the one you are trying to connect with (myuser here). In this case, peer authentication will fail. Your solution with HOST: "localhost" works because you are not using peer auth anymore. However, it is slower than HOST: "" because instead of using unix sockets, you use TCP connections. From django docs:

If you’re using PostgreSQL, by default (empty HOST), the connection to the database is done through UNIX domain sockets (‘local’ lines in pg_hba.conf). If you want to connect through TCP sockets, set HOST to ‘localhost’ or ‘127.0.0.1’ (‘host’ lines in pg_hba.conf). On Windows, you should always define HOST, as UNIX domain sockets are not available.

If you want to keep using sockets, correct settings in pg_hba.conf are needed. The most simple is:

local   all         all                               trust

while commenting out all other local lines in the config. Note that reloading postgres is needed for this change to take effect.

But if multi-user production machine is in question, you might want to use something more secure like md5 (see here for explanation of various authentication methods).


Better than fully trust is just to set it to md5.

# "local" is for Unix domain socket connections onlylocal   all         all                           md5