How to Create a PostgreSQL Database and Connect It to Django

Posted: September 29, 2024 | Updated: October 06, 2024

Step 1: Install PostgreSQL on your Computer with pgAdmin4

Download the PostgreSQL from the official website.

Install PostgreSQL with pgAdmin4 on your computer.

Open pgAdmin4.

In the left sidebar, Object Explorer windows, navigate to PostgreSQL 16 -> Databases.

Right-click and choose Create -> Database.

Enter the Database name and click the "Save" button.

Create PostgreSQL database

 

Step 2: Install psycopg2 to connect your Django app with PostgreSQL Database

pip install psycopg2

Note: Alternatively, you can use psycopg2-binary, which is easier to install but not recommended for production:

pip install psycopg2-binary

Reasons

  • psycopg2-binary includes precompiled binaries, which can lead to stability issues. If there are updates or bug fixes, they may not always be reflected immediately, potentially introducing compatibility problems.
  • The binary package can be larger than the source package, which might be unnecessary for production environments where you want to minimize dependencies.

Step 3: Add PostgreSQL Database information on your Django project

Open the main project settings.py file.

Comment the default SQLite database and add PostgreSQL database info.

#DATABASES = {
#    "default": {
#        "ENGINE": "django.db.backends.sqlite3",
#        "NAME": BASE_DIR / "db.sqlite3",
#    }
#}

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'mydatabase',  # Your database name
        'USER': 'postgres',  # Your PostgreSQL username
        'PASSWORD': 'password',  # Your PostgreSQL password
        'HOST': 'localhost',  # Set to 'localhost' for local development
        'PORT': '5432',  # Default PostgreSQL port
    }
}

Now make migrations, create super user and run the server.

© 2024 Webapptiv. All rights reserved.