Using PostgreSQL with Django

This article presents how to set up Django app with PostgreSQL. This tutorial assumes that you are using a Linux-based system, macOS or WSL and you already have Python3 with venv installed in your system. If you’re on Debian / Ubuntu based OS, then execute following command in order to update the system:

sudo apt update && sudo apt upgrade

Then install PostgreSQL along with the essential libraries by executing following command:

sudo apt install python3-dev libpq-dev postgresql postgresql-contrib

If you are using macOS, use Homebrew:

brew install postgresql

Now log into the PostgreSQL shell for the first time by entering:

sudo -u postgres psql

Once in psql shell, enter following command to create a user with password:

CREATE ROLE myuser LOGIN PASSWORD 'mypass';

And, then enter following command to create a database and assign the created user to it:

CREATE DATABASE mydatabase WITH OWNER = myuser;

Finally, type exit (or \q) and press Enter to quit psql shell. That’s it for the PostgreSQL installation and database creation part. Now let’s move onto using PostgreSQL database with Django.

First create a new folder:

mkdir myapp

Go inside this newly created folder:

cd myapp

Create virtual environment:

python3 -m venv .env

Mount virtual environment:

source .env/bin/activate

Install Django along with psycopg2:

pip install django psycopg2

Now create a project by entering following command (don’t forget the full-stop at the end):

django-admin startproject project .

Change project/settings.py as follows:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'mydatabase',
        'USER': 'myuser',
        'PASSWORD': 'mypass',
        'HOST': 'localhost',
        'PORT': '',
    }
}

Finally, run the migrations to create the necessary tables in your PostgreSQL database:

python manage.py migrate

If everything is configured correctly, Django will connect to PostgreSQL, and your mydatabase will be populated.

You may learn further about using PostgreSQL in this tutorial.

Leave a Comment