Neon + Django Integration Example

If you’re using Django, here’s what I found that works best:

pip install dj-database-url psycopg2

dj-database-url is a great package for using a single-line database connection string. You could parse the string into different chunks but I found that passing ?options=project%3D<project_id> is easiest with dj-database-url.

DATABASE_URL=postgres://<username>:<password>@<project_id>.us-east-2.aws.neon.tech/<dbname>?options=project%3D<project_id>

This would look something like DATABASE_URL=postgres://justin:myPassword@cfe-for-life-1290312.us-east-2.aws.neon.tech/cfe-db-123?options=project%3Dcfe-for-life-1290312

Then in your Django settings.py add the following:

DATABASE_URL = os.environ.get("DATABASE_URL")

if DATABASE_URL is not None:
    DATABASES = {
        'default': dj_database_url.config(
            default=DATABASE_URL,
            conn_max_age=600,
            conn_health_checks=True,
        ),
    }

I recommend using python-decouple for managing development .env files as well as production environment variables.

2 Likes

Hey @justinmitchel. Welcome! :wave:

If I understand correctly, this is a more straightforward way of connecting to a Postgres database rather than specifying the connection string variables separately (host, user, password, etc.), like our docs, right?

I’m not super familiar with Django. Is this a popular approach?

1 Like

dj-database-url is super popular and common. It was heroku’s default recommendation for Django deployments for years.

In my tests, the using the host, port, username, etc causes issues when I wasn’t local.

The connectivity issues doc is why I even thought to use dj-database-url.

1 Like

That’s great to know. Thank you so much for sharing! :smile: We’ll update our Django guide website/django.md at main · neondatabase/website · GitHub.

1 Like