Homepage of Stuart Maynes, Software Engineer

Connect Django to a Postgres database

To connect to a PostgreSQL database first make sure you have an environment variable called DATABASE_URL set to the URL of your database.

DATABASE_URL=postgres://user:password@127.0.0.1:5432/database_name

Hosts like Heroku will automatically set this when you provision the database; providing you are using Heroku Postgres1.

If you are working locally and using Pipenv you can set the config for DATABASE_URL in a .env file and it will load the .env as part of your virtual environment2.

Install the required package

To use PostgreSQL as your database in Python applications you must use the psycopg2 package3.

pipenv install psycopg2-binary

Connecting in Python

import os
import psycopg2

db = psycopg2.connect(os.environ['DATABASE_URL'], sslmode='require')

Connecting in Django

Update the connection details in settings.py, making sure to import os and urlparse from the standard library.

# settings.py
import os
from urllib.parse import urlparse

db = urlparse(os.environ['DATABASE_URL'])
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': db.path.strip('/'),
        'USER': db.username,
        'PASSWORD': db.password,
        'HOST': db.hostname,
        'PORT': db.port,
    }
}

Using a package to simplify

As an alternative to the above there is a package available called dj_database_url 4. This package parses the value of the DATABASE_URL environment variable and converts it to a dictionary that Django can use.

pipenv install dj-database-url psycopg2-binary
# settings.py
import dj_database_url

DATABASES['default'] = dj_database_url.config(conn_max_age=600, ssl_require=True)