By default, Django comes with a lightweight SQLite database system. Django describes the SQLite database as a database used just to test or familiarise oneself with Django. While this works well, it will be advisable to use a more scalable traditional database like PostgreSQL to avoid database-switch headaches down the road.
In this article, we will learn how to install and configure PostgreSQL in conjunction with Django. Let's get started.
Creating a virtual environment
The first step is to create a virtual environment to avoid collision dependency. If you don't have "virtualenv" you have to install it using the command pip install virtualenv
.
Now, let's create a virtual environment. After creating the virtual environment, we have to activate it.
Installing Django
The next step is installing Django. Django can be installed using the command pip install django
.
The next step is installing a library known as psycopg2. Pscycopg2 is a PostgreSQL database adapter for the Python programming language. In other words, psycopg2 is the database adaptor that allows Django and PostgreSQL to communicate efficiently. The command line to install it is pip install psycopg2
.
We have to create our own Django project. In our case, we will name the Django project djangopostgre
. The Django project will be created using the command line.
django-admin startproject djangopostgre
We have to change the directory by using the "cd" command.
cd djangopostgre
The next step is creating our Django application. The Django application can be created using the following command line.
python manage.py startapp testpostgre
We have succeeded in setting up our project(djangopostgre
) and building our app(testpostgre
). The next step is running the server. The server can be run using the command below:
python manage.py runserver
Setting up the PostgreSQL database server
If you don't have PostgreSQL, you can download it PostgreSQL. There are options based on your operating system. Open pgAdmin4 and click on the server, then PostgreSQL14.
Then create a database by clicking on "database". In our case, we will name the database dbpostgre.
The next step is to configure our database in the settings.py file in our code.
Name: The name you gave to the database during creation.
User: The user by default is postgre.
Password: The password is the password we used to open PostgreSQL during installation.
Host: The host is the database host. In the developmental stage, we use the local host or IP address 127.0.0.1:8000.
Port: The default port is 5432.
We have to migrate our project to the PostgreSQL database.
We have successfully created a PostgreSQL database and migrated all the Django tables to PostgreSQL.
You can check the Default table in Django on pgAdmin4. The tables are auth_group, auth_group_permisssion, auth_permission, auth_user, and many more.