How to PostgreSQL Database Connection in Django?

Published On: 21/12/2022 | Category: Django


Hi Dev,

In this short tutorial we will cover an how to postgresql database connection in django. step by step explain how to use postgresql database in python django. Here you will learn django postgresql connection example. you can understand a concept of django postgresql database connection example.

The most popular RDBMS relational database management systems are PostgreSQL and SQLite. They are both free and open-source. When choosing a database for your applications, there are a few significant distinctions to take into account.

Here i will give you we will help you to give example of how to postgresql database connection in django. So let's see the bellow example:

Step 1: Install virtualenv

In this first step Create a virtual environment first, and then use this command to instal virtualenv.

pip install virtualenv
virtualenv env
source env/bin/activate
pip install django
pip install psycopg2

Step 2: Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example
Step 3: Create a App
cd example
django-admin startapp core

Step 4: Update settings.py

Next, you need to add it in the settings.py file as follows and Now its time to switch from SQLite to PostgreSQL:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'core',
]

DATABASES = {
   'default': {
       'ENGINE': 'django.db.backends.postgresql',
       'NAME': ‘<database_name>’,
       'USER': '<database_username>',
       'PASSWORD': '<password>',
       'HOST': '<database_hostname_or_ip>',
       'PORT': '<database_port>',
   }
}

Ok, all set. We can engender a migrations file for this change, then integrate it to our database via migrate.

python manage.py makemigrations
python manage.py migrate

Let's now establish the default superuser:

python manage.py createsuperuser

Now again run the server through following command:

python manage.py runserver
http://127.0.0.1:8000/admin/

I Hope It will help you....