PostgreSQL

Last updated 1 week, 6 days

Author: sghaier

Setup PostgreSQL database for Django

When deploying a django project to production environment it is better to use PostgreSQL database. 

In the following tutorial we will go through the installation and configuration of both PostgreSQL and Django

step by step and explain how to configure both PostgreSQL and Django

Step 1 - Installing PostgreSQL 

sudo apt update

sudo apt install postgresql postgresql-contrib

After installing PostgreSQL check if the service is running correctly using the following commande

sudo service postgresql status

Step 2 - Creating the database and user which will be used by django

PostgreSQL comes with a default user called postgres which have administrator access 

we can use it to create our database and user.

To connect to PostgreSQL using the user postgres, use the following commande

 sudo -u postgres psql

Now let's create teh database which will be used by Django

postgres=# CREATE DATABASE djangoproject;

After that we need to create a new user to use it to connect to the newly created database

postgres=# CREATE USER djangouser WITH PASSWORD 'password';

Next we need to update our user and give him access to the database with all privileges

postgres=# GRANT ALL PRIVILEGES ON DATABASE djangoproject TO djangouser;

to exit the SQL prompt use the following commande

postgres=# \q

or just hit ctrl+d first you will exit the SQL prompt hit ctrl+d again and you will logout from user postgres and go back to your user

Step 3 - Update django settings to use PostgreSQL

Open Django setting.py file and navigate to the DATABASES settings

update the ENGINE and set it to django.db.backends.postgresql this tells django to use PostgreSQL backend 

Set the NAME equal to the database name we just created 'djangoproject'

Set the USER to djangouser which is the user that Django will use to connect to the database

Set the PASSWORD to the user's password set while creating the database user 

Set the HOST to localhost 

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'djangoproject',
'USER': 'djangouser',
'PASSWORD': 'password',
'HOST': 'localhost',
}
}

After that we need to install the required python packages to connect to the database

use the following commandes

pip install psycopg2
pip install psycopg2-binary 

 

Quick actions

Filter posts based on the following filters.

  • Latest Posts
  • Announcements
  • Calendars
  • etc

Seach posts by tags

Click the tag name to filter the posts