Postgres Setup
1. PostgreSQL Database Setup
Section titled “1. PostgreSQL Database Setup”Step 1: Install PostgreSQL and Dependencies
Section titled “Step 1: Install PostgreSQL and Dependencies”Install PostgreSQL (Ubuntu/Linux)
Section titled “Install PostgreSQL (Ubuntu/Linux)”sudo apt updatesudo apt install postgresql postgresql-contribInstall PostgreSQL (macOS)
Section titled “Install PostgreSQL (macOS)”brew install postgresqlbrew services start postgresqlInstall PostgreSQL (Windows)
Section titled “Install PostgreSQL (Windows)”Download from postgresql.org
Install Python PostgreSQL adapter
Section titled “Install Python PostgreSQL adapter”pip install psycopg2-binary# or for better performance:pip install psycopg2Step 2: Database Configuration
Section titled “Step 2: Database Configuration”Create Database and User
Section titled “Create Database and User”sudo -u postgres psql
# In PostgreSQL shell:CREATE DATABASE djangorestapi;CREATE USER django_user WITH PASSWORD 'securepassword123';ALTER ROLE django_user SET client_encoding TO 'utf8';ALTER ROLE django_user SET default_transaction_isolation TO 'read committed';ALTER ROLE django_user SET timezone TO 'UTC';GRANT ALL PRIVILEGES ON DATABASE djangorestapi TO django_user;\qStep 3: Update Django Settings
Section titled “Step 3: Update Django Settings”Modify config/settings.py
Section titled “Modify config/settings.py”import osfrom pathlib import Path
# DatabaseDATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'djangorestapi', 'USER': 'django_user', 'PASSWORD': 'securepassword123', 'HOST': 'localhost', 'PORT': '5432', }}
# Alternatively, use environment variables for securityDATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.getenv('DB_NAME', 'djangorestapi'), 'USER': os.getenv('DB_USER', 'django_user'), 'PASSWORD': os.getenv('DB_PASSWORD', 'securepassword123'), 'HOST': os.getenv('DB_HOST', 'localhost'), 'PORT': os.getenv('DB_PORT', '5432'), }}Step 4: Environment Variables Setup
Section titled “Step 4: Environment Variables Setup”Create .env file
Section titled “Create .env file”# Create .env file in project roottouch .envAdd environment variables to .env
Section titled “Add environment variables to .env”DEBUG=TrueSECRET_KEY=your-super-secret-key-here-make-it-very-long-and-randomDB_NAME=djangorestapiDB_USER=django_userDB_PASSWORD=securepassword123DB_HOST=localhostDB_PORT=5432Install python-dotenv
Section titled “Install python-dotenv”pip install python-dotenvUpdate settings.py to use environment variables
Section titled “Update settings.py to use environment variables”from pathlib import Pathfrom dotenv import load_dotenvimport os
# Load environment variablesload_dotenv()
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = os.getenv('SECRET_KEY', 'fallback-secret-key-for-dev')
DEBUG = os.getenv('DEBUG', 'False') == 'True'
ALLOWED_HOSTS = os.getenv('ALLOWED_HOSTS', 'localhost,127.0.0.1').split(',')
# Database configurationDATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.getenv('DB_NAME'), 'USER': os.getenv('DB_USER'), 'PASSWORD': os.getenv('DB_PASSWORD'), 'HOST': os.getenv('DB_HOST'), 'PORT': os.getenv('DB_PORT'), }}Step 5: Migrate to PostgreSQL
Section titled “Step 5: Migrate to PostgreSQL”# Create new migrationspython manage.py makemigrations
# Apply migrations to PostgreSQLpython manage.py migrate
# Create superuser for new databasepython manage.py createsuperuserStep 6: Test Database Connection
Section titled “Step 6: Test Database Connection”Create a test view to verify database
Section titled “Create a test view to verify database”# api/views.pyfrom django.db import connectionfrom rest_framework.decorators import api_viewfrom rest_framework.response import Response
@api_view(['GET'])def database_info(request): """View to check database connection info""" with connection.cursor() as cursor: cursor.execute("SELECT version(), current_database(), current_user") row = cursor.fetchone()
info = { 'database_version': row[0], 'database_name': row[1], 'database_user': row[2], 'connected': True }
return Response(info)Add to api/urls.py
Section titled “Add to api/urls.py”path('database-info/', views.database_info, name='database-info'),Test the connection
Section titled “Test the connection”curl http://127.0.0.1:8000/api/database-info/