How to properly connect PostgreSQL with Django?

I'm working on a Django project and using PostgreSQL as my database. I updated my settings.py as follows:

**

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'mydatabase',
        'USER': 'myuser',
        'PASSWORD': 'mypassword',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}

**

However, when I run python manage.py migrate, I get the following error:

django.db.utils.OperationalError: could not connect to server: Connection refused

I have PostgreSQL installed and running. I also verified that my credentials are correct. What could be the issue?

Have you installed psycopg2, **pip install psycopg2 ==2.9.9** to your dev environment, and ensure you freeze it to your requirements.txt file? You can try using 127.0.0.1 as your HOST instead of localhost, and ensure that you disable firewalls. Ensure you have created your database via using psql command and grant all privileges. Then you can go ahead and run your python manage.py migrate.

If the error persist which i doubt if you had set everything correctly, then run on your postgres bash (terminal) to diagnose further.

bash 

psql -U <myuser> -d <mydatabase> -h localhost -p 5432 
Back to Top