Django with PostgreSQL

Giavoni Giovanni
Analytics Vidhya
Published in
4 min readOct 24, 2020

--

this is a practical guide to install Django taking advantage of PostgreSQL as database solution.

For a detailed guide of Django installation steps you can also read official documentation on Django website: https://docs.djangoproject.com/en/3.1/intro/install/

Install PostgreSQL

first of all let’s open a new terminal session with the common shortcut CTRL+ALT+T.

Then just paste the following code:

# Create the file repository configuration:
sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'
# Import the repository signing key:
wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -
# Update the package lists:
sudo apt-get update
#Install the latest version of PostgreSQL.
# If you want a specific version, use 'postgresql-12' or similar instead of 'postgresql':
sudo apt-get -y install postgresql

Once installed log into the database with the command:

sudo -u postgres psql

OK, that’s right! now that you are logged-in just:

  • Create the database;
  • Create a user account and let it be let’s say “Django-friendly”;
  • Grant the user a privileged access to the database.
# create database
CREATE DATABASE your-project-name;
# create user
CREATE USER your-username WITH PASSWORD 'your-password';
# change user settings to be more "Django-friendly"
ALTER ROLE your-username SET client_encoding TO 'utf8';
ALTER ROLE your-username SET default_transaction_isolation TO 'read committed';
ALTER ROLE your-username SET timezone TO 'UTC';
# grant the user all the privileges on database
GRANT ALL PRIVILEGES ON DATABASE your-project-name TO your-username;

Where are done with setting up your PostgreSQL database. Just exit:

\q

and then close the terminal session with:

EXIT

Install Virtual Environment

it is always recommended to install Django in a virtual environment. I strongly suggest you do it. By the way at the end it’s your project so… you can jump to the next step of this tutorial if you want to change your global environment.

So first step here is to install python3 venv package (It is supposed that you have python3 already installed)

# Install virtualenv
sudo apt-get install python3-venv

After installation is done, just create a new environment for you project

# create your virtual environment
python3 -m venv your-project-name_env

Remember to always start your virtual environment later, if your wanna take advantage of all installed packages.

# activate your virtual environment
source /home/your-username/your-project-name_env/bin/activate

Now you should see (your-project-name_env) between parenthesis before username. Something like this:

(your-project_env) your-username@your-machine:~$

Install Django

# install Django
sudo apt install python3-django

The default database for a Django project is SQLite that is good for testing but is not the best choice for production mode.

In order to make PostgreSQL working fine with Django you need to install pyscopg2 package (see Django documentation for extra info: https://docs.djangoproject.com/en/3.1/topics/install/#database-installation)

# install pyscopg2 packagesudo apt install python3-dev libpq-dev
pip install psycopg2

Check the installation with the following command:

# check Django version
python3 -m django –version

Now that Django is installed, it is time for you to create your own brand new Django-project:

# create Django project
django-admin startproject your-project-name

Now move to the project folder (if you want to now what all the files mean go to Django documentation: https://docs.djangoproject.com/en/3.1/intro/tutorial01/).

and run Django server with:

# run django server
python3 manage.py runserver

If you click on the link in the terminal or if you copy and paste http://127.0.0.1:8000/ you should see the following:

Connect Django to PostgreSQL

We are there close to the end of this tutorial! last steps ahead!

Go to the Django project folder you have created before:

# open django project folder:
cd path/to/your-django-project
# browse the files (you should find something like this):
db.sqlite3 your-project-name manage.py
# go to the sub-folder your-project-name:
asgi.py __init__.py __pycache__ settings.py urls.py wsgi.py

Open the file named settings.py:

scroll to the DATABASE section (you could also find it with CRTL+F) and modify it with your database info:

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'your-project-name',
'USER': 'your-postgresql-username',
'PASSWORD': 'your-postgresql-password',
'HOST': 'localhost',
'PORT': '',
}
}

Migrate the database changes to PostgreSQL and run Django server, everything should work fine!

# apply database changes
python3 manage.py migrate
# start server
python3 manage.py runserver

Here you are done!!! congrats!

--

--

Giavoni Giovanni
Analytics Vidhya
0 Followers
Writer for

Change manager with a strong passion for coding