HOLIDAY SALE! Save 50% on Membership with code HOLIDAY50. Save 15% on Mentorship with code HOLIDAY15.

15) Use PostgreSQL, a Production-Quality Database Lesson

Connect Your Django App to Postgres

12 min to complete · By Martin Breuss

After you have successfully set up your PostgreSQL database server and got it running, you are now ready to switch your Django database backend over to using the production-quality PostgreSQL database.

Colorful illustration of a light bulb

Info: You will know that the installation was successful and that your Postgres database server is running when you are able to interact with it through psql, as described on the previous page

Django Database Settings

Django's ORM abstracts all the database interactions, and now you will see why this is a very handy feature of the framework. Different database systems have slightly different SQL syntax and other differences in how to interact with them.

Switching your database backend halfway through building a project can, therefore, be extremely complicated and require a lot of refactoring. Not with Django! Once you have your external database server set up, all you need to do is change your project's DATABASE settings appropriately, and you're using a different database backend.

Let's take a look into settings.py, where the default configuration looks like below:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'sqlite3.db',
    }
}

This setting comes as a default when you start a Django project with the startproject command. It is a sensible default setting for development, that instructs Django to use an SQLite database file named sqlite3.db as the file-based database. You've worked with this setting exclusively up to now.

Colorful illustration of a light bulb

Info: If you haven't yet started a blank new Django project for your second round of building the Polls app now is the time to do it so you can follow along with changing your database backend from the default SQLite to PostgreSQL

PostgreSQL Settings

Let's see what you will need to connect to your running Postgres database server:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'mydatabase',
        'USER': 'mydatabaseuser',
        'PASSWORD': 'mypassword',
        'HOST': '127.0.0.1',
        'PORT': '5432',
    }
}

PostgreSQL requires a couple more settings than SQLite does, so let's unpack them here:

ENGINE

This defines what package Django will use to connect to the different types of databases. It is the main setting distinguishing whether you'll be using SQLite, PostgreSQL, MySQL, etc.

NAME

This defines the name of the database that you want to use. You might have to create the database via psql before Django can connect to it and use it. Replace this value with the actual name of the database you want to use, as it is displayed on the database list when you list all available databases on your Postgres server

USER

The name of your database user. For Postgres, this might be the default user called postgres or, if you set it up, another user name

PASSWORD

The password associated with the database user that allows you to log in to your database server

HOST

The address under which your database server is accessible. For local development, this will be your localhost IP address, which is equivalent to 127.0.0.1

PORT

The port that your database server uses to communicate on the above mentioned HOST address. These differ for different database servers, and Postgres' default port is 5432

With the high-level understanding of these settings more clear, let's do the necessary work and fill in the details to allow Django to connect.

Create A New Postgres Database

To create a new database that Django will be able to connect to, let's head back over to your CLI and enter psql once again by typing:

$ psql

Make sure that you are logged in and connected to the server, and note what username shows up in the prompt. This will be the username that you need to input in the 'USER' setting in settings.py. The 'PASSWORD' will be whatever you set during your installation, and what allows you to log in to your database server, e.g. via psql.

Next, you'll want to create a new database on your server. You will use this database for your second run through building the polls app, so let's name it, fittingly, polls:

CREATE DATABASE polls;

Make sure that you can see the new database by listing the available databases with \l. If it shows up as expected, you can quite psql and head back over to your Django app's settings.py file.

Connect To Your Postgres Database

In the DATABASE section of settings.py, enter the name of your new database under the 'NAME' key. If you followed along, this will be the string 'polls'. If you haven't yet, also fill in your own data for 'USER' and 'PASSWORD'. You won't need to change the other settings. To recap, you'll need to adapt the values for:

  • 'NAME'
  • 'USER'
  • 'PASSWORD'

Once you have done that, you are ready to start using PostgreSQL as your database backend. And here's the good news: that's all! You are now connected to a fresh new Postgres database.

Everything else works as it did before. Of course, there's no data and not even any structure in there so far, but you already know how to get that set up with:

$ python manage.py migrate

By running this familiar command, Django re-creates the structure of your database as defined in your migrations/ files. Whether the instructions encoded there write to an SQLite database or a Postgres database doesn't make a difference for you, the database ENGINE handles all these implementation details.

This means that you can focus on developing your model logic in your apps without needing to worry about choosing the perfect database from the start, and it allows you to easily switch database backends, as well as use different ones in development and production.

Illustration of a lighthouse

Note: While it is convenient and common to use SQLite for local development and a different database backend in production, once your app becomes more complex it is heavily advised to use the same database server in development that you also use in production. This simply cuts out any potential subtle discrepancies that you could otherwise run into and makes your development workflow overall more stable and predictable

Ready For Polls Round 2

With your database now pointing to your new Postgres database server, you are all set for building out the Polls app again to hammer all the Django and web development concepts deeper into your brain.

You will notice that all the database interactions you will re-train to do work exactly the same as they did when using SQLite3. Pretty neat, thanks Django! Okay, now get ready for your training run without training wheels.

Summary: Django Postgres Setup

  • To create your Django to PostgreSQL database connection you need to change a handful of configurations in settings.py
  • PostgreSQL requires a USER, PASSWORD, HOST, and PORT as well as the default ENGINE and NAME settings
  • You will need to create a new database using the psql CLI before setting up your connections inside Django
  • Fill in the NAME, USER, and PASSWORD keys with the name of the database, Postgres user who created it, and their password respectively
  • Once your connection is set up, run the familiar python manage.py migrate command and Django will create the structure of your database for you