Django — Step 6

Connecting to a Postgres database

Brian Mayrose
2 min readJul 11, 2019

This is a continuation from step 5

We are going to be using a Postgres database for this project. Here is a quick installation tutorial if you are using Ubuntu:

Let’s log into postgres

sudo -u postgres psql

Then let's create a database named ‘djdemo’

create database djDemo owner postgres;

Make sure it was created

/l

To remove a database:

drop database Djdemo;

Connecting Django To Postgres

Once you have your database created and Postgres is running we can connect our Django project to it.

The first thing we need to do is install the psycopg-binary package with pip:

pip install psycopg2-binary

make sure you have your virtual environment running. We covered this in step 1.

The Psycopg is an adapter for Postgres with Python. It is mainly written in C so it is efficient and secure.

With Psycopg installed, we now can update the DATABASE sections’ key/value pairs in settings.py to use the Postgres database we set up.

By default there will be db.sqlite3 settings as keys, replace them with ENGINE, NAME, USER, PASSWORD, AND HOST and the corresponding values we used when setting up the database:

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'djDemo',
'USER': 'postgres',
'PASSWORD': 'whateverUused',
'HOST': 'localhost'
}
}

When we run python manage.py runserver we get an error about unapplied migrations:

python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.

Now that we have the database set up and connected to Django we can run the migrate command and it will remove the error.

python manage.py migrate

Now when we use the runserver command we will not get an error.

These are the default settings for the database provided by Django. We will be adding our own as we continue on with this project.

You can also use DBeaver and view the tables that were just created by Django:

Schemas >Public > Tables

Now that our project is connected to postgres the next step will be creatin a custom model for the database that we can use to upload content. We will cover this in step 7.

--

--