1) Download and install psql for your system
On Ubuntu, use apt-get:
sudo apt update
sudo apt install postgresql postgresql-contrib
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';
Create a new database(ex: “exampledb”) and grant permission to the new user:
CREATE DATABASE exampledb;
GRANT ALL PRIVILEGES ON DATABASE "exampledb" TO username;
Sign out by typing “exit” or entering the following command:
\q
3) Log in as a new user and check database connection
Log in as the newly created user:
psql -U username
Test Database with the “\c” command
\c exampledb
4) Install psycopg2-binary and update database settings
pip install psycopg2-binary
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',
}
}
5) Migrate database
python3 manage.py makemigrations
python manage.py migrate
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.
Top comments (0)