Connect a Django project to a PostgreSQL database in minutes

Apr 5, 2024

Want to use PostgreSQL in your Django project? Check out this simple tutorial

First of all, I assume that you have already performed the following steps:

Installed Python > https://www.python.org/downloads/ Installed Django > https://docs.djangoproject.com/en/5.0/topics/install/ Installed PostgreSQL > https://www.postgresql.org/download/ Created a Django project > https://docs.djangoproject.com/en/5.0/intro/tutorial01/

If you have completed all these steps, then you can start with this tutorial:

First step: Requirements

To use PostgreSQL with Django, we have to install "psycopg". It is the most popular PostgreSQL adapter for the Python programming language. Run the following command in your project environment:

pip install psycopg2-binary

Second step: Create Database

The next step is to create our database and user. I will use pgAdmin (PostgreSQL desktop app) to create the database and then my user.

  • Open pgAdmin
  • Right click on "Databases", then select "Create/Database…"
  • Choose the name of your database and click the "Save" button.
pgAdmin

After this, we already have our PostgreSQL database created.

Now, we have to create a user to interact with our database.

  1. Right click on your database name and then click on "CREATE Script"
pgAdmin
  1. Copy and paste the following PostgreSQL script into your pgAdmin app:
CREATE USER user_name WITH LOGIN PASSWORD 'password' VALID UNTIL 'infinity';

Don't forget to change the fields "user_name" and "password" for your own name and password. Then, execute the script.

Now, we have to grant privileges to our user:

  1. Press right click on your user name then go to "Properties…"
pgAdmin
  1. Go to "Privileges" and switch the button "Superuser?".
pgAdmin

Then, we've already configured our database and our user.

Third step: Setup Django

Now we have to setup our Django project.

  1. Go to settings.py file on your project folder and look the following block of code:
DATABASES = {
 'default': {
     'ENGINE': 'django.db.backends.sqlite3',
     'NAME': BASE_DIR / 'db.sqlite3',
 }
}
  1. Replace it for the following code:
DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql_psycopg2",
        "NAME": "database_name",
        "USER": "user_name",
        "PASSWORD": "password",
        "HOST": "localhost",
        "PORT": "",
    }
}

Don't forget to replace the fields NAME, USER and PASSWORD with the name of your database, your username and your password.

Fourth Step: Test it

Run the following scripts in your project to test if your Django project is connected to the PostgreSQL database.

python3 manage.py makemigrations
python3 manage.py migrate

So, you got to see something like this:

pgAdmin

You already have your PostgreSQL database connected to your Django project!

Thanks for reading!

Franco Gidaszewski