connect to a DB using psycopg2 without password


Question

I have a postgres database on my localhost I can access without a password

$ psql -d mwt
psql (8.4.12)
Type "help" for help.

mwt=# SELECT * from vatid;
  id   | requester_vatid |...
  -----+-----------------|...   
  1719 | IT00766780266   |...

I want to access that database from django. So I put in DATABASES

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'mwt',
        'USER': 'shaoran',
        'HOST': 'localhost'
    }
}

Since I don't need a password to access my test database I didn't provide any PASSWORD value in the settings.

$ ./manage.py shell
>>> from polls.models import Vatid
>>> Vatid.objects.all()
  connection_factory=connection_factory, async=async)
  OperationalError: fe_sendauth: no password supplied

I tried using PASSWORD: '' but I get the same error message. I tried to use PASSWORD: None but that didn't help either.

I've been searching the django documentation about this but I cannot find anything useful. It is possible to configure django.db.backends.postgresql_psycopg2 to accept empty password?

1
43
2/21/2018 4:12:45 PM

Accepted Answer

Check your pg_hba.conf to allow connection from localhost by user shaoran, then either provide the password of shaoran in Django settings or trust the user in pg_hba.conf

The fact that you could connect through psql is because psql -d mwt uses some default connection values which are set as trusted in pg_hba.conf. For example, on my machine, the default host is local socket instead of localhost

12
6/25/2012 3:36:53 PM

Surprisingly, the answer is to not specify a host at all. If you do this,

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'mwt',
    }
}

Then psycopg2 will connect using a Unix socket in the same manner as psql. When you specify a HOST, psycopg2 will connect with TCP/IP, which requires a password.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon