DEV Community

Abby Nduta
Abby Nduta

Posted on • Updated on

Setting up PostgreSQL on a Django/Python project

Postgres is a popular relational database that you can use in your Python/Django project. Setting it up however, can be a little overwhelming.

Graciously, with Django models, you don’t have to write too many SQL queries to create your database, tables and even add data on your psql shell.

Here is your step by step summary to install and set up PostgreSQL on Ubuntu 22.04:

Check whether Postgres is installed

  • Open a terminal or command prompt.
  • Run the following command:
 psql --version
Enter fullscreen mode Exit fullscreen mode
  • The version information will be displayed in the output.

Install Postgres

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

Start the PostgreSQL service

sudo systemctl start postgresql.service
Enter fullscreen mode Exit fullscreen mode

Switch over to the postgres account

sudo -i -u postgres
Enter fullscreen mode Exit fullscreen mode

Access the psql shell

psql
Enter fullscreen mode Exit fullscreen mode

Create a superuser role with login privileges, and password

 CREATE ROLE <name_of_role> LOGIN PASSWORD <password_as_a string> BYPASSRLS;
Enter fullscreen mode Exit fullscreen mode

Create database

CREATE DATABASE <database_name>;
Enter fullscreen mode Exit fullscreen mode

Grant privileges on the database

GRANT ALL PRIVILEGES ON DATABASE <database_name> TO <created_superuser>;
Enter fullscreen mode Exit fullscreen mode

Connect to the database (outside of psql and user postgres)

psql -U payments_admin -h localhost -p 5433 -d payments;
Enter fullscreen mode Exit fullscreen mode

That's it, you are now ready to start going migrations to your database, and create tables based on your Django models.

Top comments (0)