Configure PostgreSQL With Django Application On CentOS 7

Django is a high level and flexible Python web framework. It is a free and open source tool used to store data into a lightweight SQLite database file. In this article, we will explain how you can make the installation and configuration of PostgreSQL in order to be able to use it with Django applications.

In this tutorial, let us see how to Configure PostgreSQL With Django Application On CentOS 7.

Introduction to PostgreSQL

PostgreSQL is an open source object relational database system. It has been released since 15 years, during which it earned a strong reputation for its reliability, data integrity and correctness. PostgreSQL could be used with all existing operating systems, such Linux, UNIX and windows. All the data types are existed with this tool such INTEGER, NUMERIC, BOOLEAN, CHAR, VARCHAR, DATE, and others. This tool also supports storage of binary large objects, including pictures, sounds and videos.

Before starting it is required to have a clean CentOS 7 server instance with a non-root user set up which also must be configured using “sudo” privileges”.

Configure PostgreSQL With Django Application

Install the needed components from repositories:

We will start our tutorial by installing all the needed components from our CentOS and EPEL repository. So we will need the “pip”, python package manager, the database software and the associated libraries to interact with them. As it is mentioned those components will be installed from the CentOS and EPEL repository. So to enable the EPEL repository you have just to use the following command:

sudo yum install epel-release

To install the required components, the following command is used:

sudo yum install python-pip python-devel gcc postgresql-server postgresql-devel postgresql-contrib

Configure the PostgreSQL:

To initialize the PostgreSQL database, the following command is used:

sudo systemctl start postgresql

After the initialization of the PostgreSQL database, now we will make some adjustment of the configuration files. Choose your editor the “sudo” command and type as below:

sudo nano /var/lib/pgsql/data/pg_hba.conf

Using this command you will open the file which is responsible of the authentication methods for the database system. For local maintenance tasks, the type of connection used with it can be accepted but for a Django project isn’t the case since a user configuration is with a password. In order to adjust this we will edit the “host” lines. Just the last column will be replaced by “md5” which will allow the password authentication:

# TYPE  DATABASE        USER            ADDRESS                 METHOD
# "local" is for Unix domain socket connections only
local   all             all                                     peer
# IPv4 local connections:
#host    all             all             127.0.0.1/32            ident
host    all             all             127.0.0.1/32            md5
# IPv6 local connections:
#host    all             all             ::1/128                 ident
host    all             all             ::1/128                 md5

Now we will restart the service using:

sudo systemctl restart postgresql

sudo systemctl enable postgresql

Create database and database user:

There is an operating system named “postgres” was created during the installation of the Postgres to correspond to the postgres PostgreSQL administrative user. So it is required to change to this user to be able to perform administrative tasks using:

sudo su - postgres

To log in the Postgres session use the following command:

psql

Now we will create our database for the Django project. We will name it “projectdata”:

CREATE DATABASE projectdata;

It is important to finish each command at SQL with semicolon. Now we will create a database user which will be used to connect to and interact with the database, you have to enter your password here:

CREATE USER projectdatauser WITH PASSWORD 'password';

We will make some changes for the connection parameters using the following command:

ALTER ROLE projectdatauser SET client_encoding TO 'utf8';
ALTER ROLE projectdatauser SET default_transaction_isolation TO 'read committed';
ALTER ROLE projectdatauser SET timezone TO 'UTC';

Now we will give our database user access rights to the database already created using the following command:

GRANT ALL PRIVILEGES ON DATABASE myproject TO myprojectuser;

Then type the following command to exit the SQL prompt:

\q

And the following command is used to exit the postgres user’s shell session.

exit

Installation of Django:

Now we will start the installation of our Django and all its dependencies within Python virtual environment. To get the virtual environment package use the following command:

sudo pip install virtualenv

Then type the following command to make a directory for holding your Django project:

mkdir ~/projectdata
cd ~/projectdata

And to create your virtual environment type:

virtualenv projectdataenv

Now we will activate the applications that will be installed within the virtual environment using the following command:

source projectdataenv/bin/activate

You will remark that your prompt will be changed showing you that you are now operating with your virtual environment:

(projectdataenv)user@host:~/projectdata$.

Now we will install the Django and the “psycopg2” package using the “pip” command:

pip install django psycopg2

Using the “projectdata” created directory, we can start our Django project using the following command:

django-admin.py startproject projectdata .

Configure Django database settings:

Now we will configure our project in order to use the created database. We will open the main Django project settings file using the following command:

nano ~/projectdata/projectdata/settings.py

At the end of this file there is a “DATABASES” section which is configured to SQLite as a database.

DATABASES = {
   'default': {
       'ENGINE': 'django.db.backends.sqlite3',
       'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
   }
}

We will change this section that the PostgreSQL database will be used instead of SQLite.

We will do as below:

DATABASES = {   'default': {
       'ENGINE': 'django.db.backends.postgresql_psycopg2',
       'NAME': 'projectdata',
       'USER': 'projectdatauser',
       'PASSWORD': 'password',
       'HOST': 'localhost',
       'PORT': '',
   }
}

Then save and close the file.

Test our project:

Now we will test our Django project starting by the migration of our data structures to our database using the following command:

cd ~/projectdata
python manage.py makemigrations
python manage.py migrate

Then type the following command to create an administrative account while you will be asked to choose a username, an e-mail address and a password:

python manage.py createsuperuser

now we will start our Django project using the following command:

python manage.py runserver 0.0.0.0:8000

In your web browser, visit your server’s domain name or IP address followed by :8000 to reach default Django root page:

http://server_domain_or_IP:8000

Then add the “/admin” to the end of the URL, that you be in front of the login screen. So enter your username and password already created that you will be taken to the admin interface. You can stop the development server using the Ctrl-C on your terminal window.

Now our user account information was stored in our database and it can be appropriately been accessed.

Conclusion

The installation and configuration of the PostgreSQL was described in this article. This tool can be used as the backend database for a Django project.