dj-database-url
dj-database-url is a simple Django utility that allows you to configure your Django application's database using a single 12-factor inspired `DATABASE_URL` environment variable. It parses the URL and returns a Django-compatible database connection dictionary, supporting various backend types like PostgreSQL, MySQL, SQLite, and Oracle. Currently at version 3.1.2, it is actively maintained by the Jazzband community with regular updates.
Warnings
- breaking Version 3.0.0 introduced a new decorator registry pattern for database connection string checks and broke some API compatibility. It also updated supported Python and Django versions.
- breaking Version 2.3.0 removed support for Python 3.8 and Django 3.
- gotcha For performance and reliability in production, it's highly recommended to explicitly set `conn_max_age` (for persistent connections) and `conn_health_checks` (for checking connection validity) when using `dj_database_url.config()`.
- gotcha When connecting to SQLite with an absolute file path, ensure you use four slashes (e.g., `sqlite:////full/path/to/your/database/file.sqlite`). The extra slashes are necessary because the 'file' portion is treated as the database's filename, not a hostname.
- gotcha Oracle database URLs expect the format `user:password` separated by a colon, not a forward slash as sometimes seen in other Oracle tools. You can also omit `HOST` and `PORT` and provide a full DSN string or TNS name in the `NAME` part of the URL.
- gotcha `dj_database_url.config()` will raise a `UserWarning` if no `DATABASE_URL` environment variable is set and no `default` URL is provided in the function call.
Install
-
pip install dj-database-url
Imports
- config
from dj_database_url import config
- parse
from dj_database_url import parse
Quickstart
import os
import dj_database_url
# In your Django settings.py
DATABASES = {
'default': dj_database_url.config(
default=os.environ.get('DATABASE_URL', 'sqlite:///db.sqlite3'),
conn_max_age=600,
conn_health_checks=True,
)
}
# Example of how DATABASE_URL might be set in your environment (e.g., .env file or deployment config)
# export DATABASE_URL="postgres://user:password@host:port/dbname"
# export DATABASE_URL="sqlite:///path/to/my/db.sqlite3"