DEV Community

Cover image for Postgresql and Django Quickstart Guide
Ordinary Coders
Ordinary Coders

Posted on • Originally published at ordinarycoders.com

Postgresql and Django Quickstart Guide

1) Download and install psql for your system
On Ubuntu, use apt-get:

sudo apt update
sudo apt install postgresql postgresql-contrib
Enter fullscreen mode Exit fullscreen mode

2) Create new user and database in the SQL Shell
Login as “postgres” user and create a new user with the following command (replacing “username” and “jws8s0F4” with the appropriate values”:

psql -U postgres

# after logged in as postgres
CREATE USER username WITH PASSWORD 'jw8s0F4';
Enter fullscreen mode Exit fullscreen mode

Create a new database(ex: “exampledb”) and grant permission to the new user:

CREATE DATABASE exampledb;
GRANT ALL PRIVILEGES ON DATABASE "exampledb" TO username;
Enter fullscreen mode Exit fullscreen mode

Sign out by typing “exit” or entering the following command:

\q
Enter fullscreen mode Exit fullscreen mode

3) Log in as a new user and check database connection
Log in as the newly created user:

psql -U username
Enter fullscreen mode Exit fullscreen mode

Test Database with the “\c” command

\c exampledb
Enter fullscreen mode Exit fullscreen mode

4) Install psycopg2-binary and update database settings

pip install psycopg2-binary
Enter fullscreen mode Exit fullscreen mode

In the example below, values are secured using python decouple:

# make sure to pip install psycopg2-binary
#in settings.py

DATABASES = {
     'default': {
        'ENGINE': 'django.db.backends.postgresql', #some guides include the psycog2 part in the name
        'NAME': config('DB_NAME'),  #includes python decouple
        'USER': config('DB_USER'),
        'PASSWORD': config('DB_PASSWORD'),
        'HOST':'localhost',
        'PORT': '5432',
    }
}
Enter fullscreen mode Exit fullscreen mode

5) Migrate database

python3 manage.py makemigrations
python manage.py migrate
Enter fullscreen mode Exit fullscreen mode

If you can successfully migrate your database, then setup is complete. If unable to migrate, ensure all database configurations are correct and no typos exist.

More information

Top comments (0)