Django’s built-in ORM supports connecting to external relational databases—such as PostgreSQL, MySQL, SQLite, Oracle, and others—via the DATABASES
setting in settings.py
. Proper configuration ensures secure, performant access for development and production environments.
1. Configure DATABASES
in settings.py
Define connection parameters under the DATABASES
dictionary. For PostgreSQL:
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mydb', 'USER': 'dbuser', 'PASSWORD': 's3cr3t', 'HOST': 'db.example.com', 'PORT': '5432', 'OPTIONS': { 'sslmode': 'require', }, } }
Supported ENGINE
values:
django.db.backends.postgresql
,
django.db.backends.mysql
,
django.db.backends.oracle
,
django.db.backends.sqlite3
(file),
plus third-party backends (e.g., Microsoft SQL Server).
2. Manage Credentials Securely
Avoid hard-coding credentials. Leverage environment variables or a secrets manager:
import os DATABASES = { 'default': { 'ENGINE': os.getenv('DB_ENGINE', 'django.db.backends.postgresql'), 'NAME': os.getenv('DB_NAME'), 'USER': os.getenv('DB_USER'), 'PASSWORD': os.getenv('DB_PASS'), 'HOST': os.getenv('DB_HOST'), 'PORT': os.getenv('DB_PORT'), } }
3. Enable SSL/TLS for Secure Connections
Configure SSL options to encrypt traffic:
'OPTIONS': { 'sslmode': 'verify-full', 'sslrootcert': '/path/to/ca.crt', },
OPTIONS: {'ssl': {'ca': '/path/ca.pem'}}
. Verify your database’s SSL support in PDF driver documentation.4. Use Connection Pooling for Performance
Django opens a new connection per request by default. For high traffic, integrate pooling via:
- django-db-geventpool: gevent-based pool
- django-postgrespool2: psycopg2 pool support
- SQLAlchemy as an alternative ORM with built-in pooling
Example with django-postgrespool2:
DATABASES['default']['ENGINE'] = 'django_postgrespool2'
5. Migrate and Test the Connection
Apply migrations and verify connectivity:
python manage.py migrate python manage.py dbshell
dbshell
to open a SQL shell with your configured database driver.6. Troubleshooting Common Issues
- Authentication errors: Check credentials and host reachability.
- SSL failures: Validate certificates and
sslmode
settings. - Driver not installed: Install
psycopg2
for PostgreSQL,mysqlclient
for MySQL, orcx_Oracle
for Oracle. - Timeouts: Increase
CONN_MAX_AGE
or database-side timeout settings.
7. Summary Checklist
- Define
DATABASES
with appropriateENGINE
and connection parameters. - Secure credentials via environment variables or secret managers.
- Enable SSL/TLS using
OPTIONS
and valid certificates.[PDF Driver SSL Guide] - Integrate connection pooling for high-throughput applications.
- Run
migrate
anddbshell
to verify connectivity. - Install and configure database drivers per PDF-backed documentation.