Python with Django

Connecting with Django

Steps

  1. Create your Crunchy Bridge Postgres Cluster
  2. Connect your Django to Postgres
  3. Confirm your app is connecting to your database

Create your Crunchy Bridge Postgres cluster

Creating a Crunchy Bridge cluster is pretty simple. Log into your Crunchy Bridge account, and click “Create Cluster”, then follow the cluster create form.

From here, we’ll want to get a “connection string” that we can use later. It looks like this:

postgres://user:password@host:port/database?setting=value

Once your Postgres cluster has a status of “ready” (a few minutes), click on the “Connections” tab for your connection string.

We will set this value as a DATABASE_URL value later when connecting to the database.

Configure Django for Postgres

There are two main forms of connecting your Postgres database to your Django app, one is with the helper dj_database_url library the other by manually parsing your database connection string.

Option 1: Connecting to Postgres with dj_database_url

First start by installing the libary.

pip install dj-database-url

Note: Ensure that both dj-database-url and psycopg2-binary are both in your requirements.txt file

You'll then want to make sure the dj_database_url library is imported

import dj_database_url

The dj_database_url library will automatically pick up the DATABASE_URL environment variable, so if you've set it within your environment then later in your settings file you can simply load it with the following:

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

Option 2: Connecting to Postgres via environment variable

If you do not want to use dj_database_url you can parse the DATABASE_URL environment variable and load the values into your Django settings. First, you'll want to make sure the appropriate libraries are installed, then you'll want to parse the environment variable and load it into the settings:

import psycopg2-binary
import os

#...

url = urlparse(os.environ['DATABASE_URL'])
username = url.username
password = url.password
database = url.path[1:]
hostname = url.hostname
port = url.port

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': database,
        'USER': username,
        'PASSWORD': password,
        'HOST': hostname,
        'PORT': port,
    }
}

Confirm app is connecting to database

You can confirm your app is fully connecting by launching a shell and running a basic query.

First launch a shell:

python manage.py runserver

Now we'll run a basic query:

SELECT 1;

If all worked, you've got a database now fully connected and can get back to building your application. Feel free now to go ahead and run your migrations for your app.