Install psycopg2
, the PostgreSQL adapter for Python, by running the following command in your terminal:
pip install psycopg2
You can also use psycopg2-binary
for a precompiled version:
pip install psycopg2-binary
-
Log into PostgreSQL as a superuser:
psql -U postgres
-
Create a new database (replace
my_database
with your desired database name):CREATE DATABASE my_database;
-
Exit the PostgreSQL prompt:
\q
-
Log back into PostgreSQL:
psql -U postgres
-
Create a new role (replace
my_user
andmy_password
with your desired username and password):CREATE ROLE my_user WITH LOGIN PASSWORD 'my_password';
-
Grant the new role privileges to create databases and connect to the existing database:
ALTER ROLE my_user CREATEDB; GRANT CONNECT ON DATABASE my_database TO my_user;
-
Exit the PostgreSQL prompt:
\q
-
Open your Django project and locate the
settings.py
file. -
Update the
DATABASES
setting to include your new database and role:DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'my_database', # Your new database name 'USER': 'my_user', # Your new role name 'PASSWORD': 'my_password', # Your new role password 'HOST': 'localhost', # Or your database host 'PORT': '5432', # Default PostgreSQL port } }
Run the following command to apply migrations and set up the database schema:
python manage.py migrate
You have successfully set up PostgreSQL in your Django project, created a new database, created a new role, and connected that role to the database. If you encounter any issues, check the console output for error messages and ensure that your PostgreSQL service is running.