Django is a high-level framework for python. It’s one of the most flexible frameworks to quickly create the application. In default, Django application is configured to store data into SQLite Database. 

In this article, We will demonstrate how to install and Configure Postgres on Django application.

Here, we will install the necessary software and packages, we will create the database for our application and set up the new Django project to use in backend. 

Installing the Necessary Component. 

We will Install all the necessary things that we need from repositories. At first, We will install PIP python packages manager to install and manages the python component. 

We will also install the database software and repositories required to configure the database. 

The following command will install all the necessary packages you need.  

sudo apt-get update 
sudo apt-get install python-pip python-dev libpq-dev postgresql postgresql-contrib

Install psycopg2

pip install psycopg2

We need to install PostgresSQL Database adapter to communicate with python programming. To install run the following command to the shell;

Create a PostgreSQL User and Database

By default, PostgresSQL uses the user Postgres. and the user Postgres has full user admin access to entire Postgres instance running on your OS.

sudo -u postgres psql 

Now terminal will be prefixed with postgres=#, The above command will get you the psql command-line interface with full admin access.

Now let’s create a database and user.

Creating Database

CREATE DATABASE project;

The above statement will create the database project. Remember, You every SQL statement should end with Semicolon.

Creating User

CREATE USER root WITH ENCRYPTED PASSWORD 'password';

Here, the above statement creates the user root with Password password. You can use username and password according to your wish.

Modifying connection Parameter

 ALTER ROLE myuser SET client_encoding TO 'utf8';
 ALTER ROLE myuser SET default_transaction_isolation TO 'read committed';
 ALTER ROLE myuser SET timezone TO 'UTC';
We are setting the default encoding to UTF-8 which Django expects.

We are also setting the default transaction default isolation scheme to “read committed” which blocks reads from uncommitted transactions.

Lastly, We are setting the timezone by default, our Django project will set to use UTC. These are the essentials parameter recommended by official Django Team

Granting Permission to the User.

GRANT ALL PRIVILIGES ON DATABASE project TO root;

Now, our user has administrative access to the database.

Now exit the SQL prompt

\q

Integrating Postgres With Django application

After creating a Django project, go to Setting.py file of your project and scroll to the database section. You will see the following piece of code there.

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

Update these setting with below code to integrate Postgres on our project.

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

Let’s look over the setting.

DATABASES: The databases variable defines the key-value pair. Each key represents a database reference name and values is a python dictionary with database connection parameter.

Default: The default the reference name is used to indicate that any database related operation declared in a Django project be executed against this connection. This means that unless otherwise specified, all database CRUD (Create-Read-Update-Delete) operations are done against the database defined with the default key.

Engine: Engine is one of the most important parameters of the Django database connection. Here ‘ENGINE’: ‘django.db.backends.postgresql_psycopg2’, tells the Django to use Postgres Backend. Depending on the database brand you plan to use for a Django application, the ENGINE value has to be one of the values

Name: Name refers to your database name.

USER: User refers to your database user name

PASSWORD: Password refers to your database your password.

HOST: The host refers to the address of the database server you want to connect.

PORT: The port you want to connect. The default port of Postgres is ‘5432’

Testing the Database Connection

After updating the database configuration, it’s time to test the connection.

During the first migration against the database, there are series of migration Django requires that create tables to keep track of administration and sessions.

In the directory, Where manage.py scripts exist and run the following commands:

Python manage.py makemigration
Python manage.py migrate

After running the following scripts if everything works well you will see the following output:

Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying sessions.0001_initial... OK