Setting Up PostgreSQL Database for a Django Project
Setting Up PostgreSQL Database for Django Project on Ubuntu
Follow these steps to configure a PostgreSQL database for your Django project on an Ubuntu server. This guide ensures that the database setup aligns with Blocksport.com’s project standards.
1. Access PostgreSQL
Open a terminal on your Ubuntu server and enter the PostgreSQL shell:
sudo -u postgres psql
You may be prompted to provide the system's admin password.
2. List Existing Databases
To verify existing databases, use:
\l
Press q to exit the list and return to the PostgreSQL shell.
3. Create a New Database
Create a dedicated database for the Django project:
CREATE DATABASE blocksport_tenant;
4. Create a Database User
Define a new user for database access and assign a secure password:
CREATE USER blocksport_tenant WITH PASSWORD 'blocksport_password';
Replace 'blocksport_password' with a strong password for security.
5. Connect to the Database
Switch to the newly created database:
\c blocksport_tenant
This connects you to the blocksport_tenant database.
6. Create a Schema
Set up a schema associated with the new user:
CREATE SCHEMA blocksport_tenant AUTHORIZATION blocksport_tenant;
7. Configure Role Settings
Customize the user's role for better compatibility with Django:
a. Set Client Encoding to UTF-8:
ALTER ROLE blocksport_tenant SET client_encoding TO 'utf8';
b. Set the Timezone to UTC:
ALTER ROLE blocksport_tenant SET timezone TO 'UTC';
c. Set the Database Search Path:
Ensure the schema is included in the search path:
ALTER ROLE blocksport_tenant IN DATABASE blocksport_tenant SET search_path = blocksport_tenant;
8. Exit PostgreSQL
Once the setup is complete, exit the PostgreSQL shell:
\q
9. Update Django Settings
Update the DATABASES dictionary in your Django project's settings.py to match the PostgreSQL configuration:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'blocksport_tenant', # Database name
'USER': 'blocksport_tenant', # Database user
'PASSWORD': 'blocksport_password', # Replace with the password
'HOST': 'localhost', # Use '127.0.0.1' or 'localhost'
'PORT': '5432', # Default PostgreSQL port
}
}
10. Apply Migrations
Run the following Django management commands to create the necessary database tables:
python manage.py makemigrations
python manage.py migrate
11. Test the Setup
Start the Django development server and ensure the database connection works:
python manage.py runserver
Comments
Post a Comment