Connect Django to Database
Connecting your Django application to AWS RDS PostgreSQL
🔌 What is Database Connection?
Database connection links your Django application to AWS RDS PostgreSQL. Django uses connection settings to communicate with the database, enabling data storage, retrieval, and management for your web application.
# Django connects to database using settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'djangodb',
}
}
Connection Components
Credentials
Username and password for access
USER = 'admin'
PASSWORD = 'yourpassword'
Host
RDS endpoint URL
HOST = 'mydb.rds.amazonaws.com'
Port
Database connection port
PORT = '5432'
Database Name
Specific database to use
NAME = 'djangodb'
🔹 Step 1: Install PostgreSQL Adapter
Install psycopg2, the PostgreSQL adapter for Python. This package allows Django to communicate with PostgreSQL databases. Use the binary version for easier installation without compilation requirements.
# Install psycopg2-binary (recommended for development)
pip install psycopg2-binary
# Or install psycopg2 (requires PostgreSQL installed locally)
pip install psycopg2
# Verify installation
pip list | grep psycopg2
Installation Notes:
- psycopg2-binary: Pre-compiled, easy to install
- psycopg2: Requires compilation, better for production
- Add to requirements.txt for deployment
🔹 Step 2: Get RDS Connection Details
Retrieve your RDS database connection information from the AWS Console. You'll need the endpoint URL, port, database name, and credentials you set during RDS creation.
How to Find RDS Details:
- Go to AWS RDS Dashboard
- Click on your database instance
- Find "Connectivity & security" section
- Copy the Endpoint URL
# Example RDS Connection Details:
Endpoint: mydjangodb.c9akciq32.us-east-1.rds.amazonaws.com
Port: 5432
Database Name: djangodb
Master Username: admin
Master Password: YourSecurePassword123!
🔹 Step 3: Update Django Settings
Configure Django's database settings to connect to your RDS instance. Replace the default SQLite configuration with PostgreSQL settings using your RDS connection details.
# settings.py
# Replace the default DATABASES configuration with:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'djangodb',
'USER': 'admin',
'PASSWORD': 'YourSecurePassword123!',
'HOST': 'mydjangodb.c9akciq32.us-east-1.rds.amazonaws.com',
'PORT': '5432',
}
}
Configuration Parameters:
- ENGINE: Database backend (PostgreSQL)
- NAME: Database name from RDS
- USER: Master username
- PASSWORD: Master password
- HOST: RDS endpoint URL
- PORT: PostgreSQL port (5432)
🔹 Step 4: Use Environment Variables (Recommended)
Store sensitive database credentials in environment variables instead of hardcoding them. This approach enhances security and makes it easier to manage different configurations for development and production environments.
# Create .env file in project root
DB_NAME=djangodb
DB_USER=admin
DB_PASSWORD=YourSecurePassword123!
DB_HOST=mydjangodb.c9akciq32.us-east-1.rds.amazonaws.com
DB_PORT=5432
# Install python-decouple
pip install python-decouple
# settings.py
from decouple import config
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': config('DB_NAME'),
'USER': config('DB_USER'),
'PASSWORD': config('DB_PASSWORD'),
'HOST': config('DB_HOST'),
'PORT': config('DB_PORT'),
}
}
Security Best Practices:
- Add .env to .gitignore
- Never commit credentials to version control
- Use different credentials for production
- Rotate passwords regularly
🔹 Step 5: Test Database Connection
Verify that Django can successfully connect to your RDS database. This test ensures all connection parameters are correct before running migrations or creating database tables.
# Test connection using Django shell
python manage.py shell
# In Django shell, run:
from django.db import connection
cursor = connection.cursor()
print("Database connection successful!")
# Exit shell
exit()
Troubleshooting Connection Issues:
- Check RDS security group allows your IP
- Verify endpoint URL is correct
- Ensure database is in "Available" status
- Confirm credentials are correct
- Check if psycopg2 is installed
🔹 Step 6: Run Migrations
Create database tables by running Django migrations. Migrations translate your Django models into database tables in your RDS PostgreSQL instance, setting up the schema for your application.
# Create migration files
python manage.py makemigrations
# Apply migrations to RDS database
python manage.py migrate
# You should see output like:
# Running migrations:
# Applying contenttypes.0001_initial... OK
# Applying auth.0001_initial... OK
# Applying admin.0001_initial... OK
# ...
Expected Output:
Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying sessions.0001_initial... OK
🔹 Step 7: Create Superuser
Create an admin user to access Django's admin interface. This superuser account allows you to manage your application's data through Django's built-in administration panel.
# Create superuser
python manage.py createsuperuser
# You'll be prompted for:
# Username: admin
# Email: [email protected]
# Password: (enter secure password)
# Password (again): (confirm password)
# Success message:
# Superuser created successfully.
🔹 Step 8: Verify Connection in Admin
Test the complete setup by accessing Django's admin interface. This confirms that Django is successfully reading and writing data to your RDS database through the web interface.
# Start Django development server
python manage.py runserver
# Open browser and go to:
# http://127.0.0.1:8000/admin/
# Log in with superuser credentials
# You should see the Django admin dashboard
Success Indicators:
- ✓ Admin login page loads
- ✓ Can log in with superuser credentials
- ✓ Admin dashboard displays correctly
- ✓ Can view and edit database records
🔹 Connection Options
Configure additional connection parameters for better performance and reliability. These optional settings help optimize database connections, handle timeouts, and enable SSL encryption for secure communication.
# settings.py - Advanced configuration
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': config('DB_NAME'),
'USER': config('DB_USER'),
'PASSWORD': config('DB_PASSWORD'),
'HOST': config('DB_HOST'),
'PORT': config('DB_PORT'),
'OPTIONS': {
'connect_timeout': 10,
'sslmode': 'require',
},
'CONN_MAX_AGE': 600, # Connection pooling
}
}
Optional Parameters:
- connect_timeout: Connection timeout in seconds
- sslmode: SSL connection mode (require/prefer/disable)
- CONN_MAX_AGE: Connection lifetime in seconds