Using PostgreSQL with Django

Django is a high level full-stack open-source web framework written in Python, that encourages rapid development and clean, pragmatic design.

Django, in its ‘out-of-the-box’ state, is set up to communicate with SQLite – a lightweight relational database included with the Python distribution. So by default, Django automatically creates an SQLite database for your project.

In addition to SQLite, Django also has support for other popular databases that include PostgreSQL, MySQL, and Oracle.

However, PostgreSQL has a number of features that are not shared by the other databases Django supports, which makes it an idle choice for a Django app in production.

In this article, we will go through the integration of PostgreSQL with a Django Application.


We are assuming you already have Django installed on your machine and one Django project up and running, if not then read the following article – Starting A Django Project

Installing PostgreSQL

Windows and macOS X users can download PostgreSQL from the official site and simply install it.

Note that tutorial is strictly based on Python 3

Linux User

sudo apt-get install postgresql postgresql-contrib

Also, Linux users need to install some dependencies for PostgreSQL to work with Python.

sudo apt-get install libpq-dev python3-dev

Install psycopg2

Next, we need to install the PostgreSQL database adapter to communicate to the database with Python to install it run the following command in the shell.

pip install psycopg2

Create A PostgreSQL User and Database

As the default configuration of Postgres is, a user called Postgres is made on, and the user Postgres has full super admin access to entire PostgreSQL instance running on your OS.

sudo -u postgres psql

Now the terminal should be prefixed with postgres=# , The above command gets you the psql command-line interface in full admin mode.

Now let’s create a user and database.

Creating Database


This will create a database named mydb, note that every SQL statement must end with a semicolon.

Creating User


Here we are creating a user named myuser with password mypass. You can use any username and password you wish.

Modifying Connection Parameters

 ALTER ROLE myuser SET client_encoding TO 'utf8';
 ALTER ROLE myuser SET default_transaction_isolation TO 'read committed';
 ALTER ROLE myuser SET timezone TO 'UTC';

We are setting the default encoding to UTF-8, which Django expects.

We are also setting the default transaction isolation scheme to “read committed”, which blocks reads from uncommitted transactions.

Lastly, we are setting the timezone by default, our Django projects will be set to use UTC.These are essential parameters recommended by the official Django team.

Granting Permission To The User


Now our user has administrative access to the database.

Now exit the SQL prompt.


Integrating PostgreSQL With Django

Open the file of your project and scroll straight to the database section, which should look like this.

    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),

We need to update these settings to integrate our PostgreSQL with the project.

    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'mydb',
        'USER': 'myuser',
        'PASSWORD': 'mypass',
        'HOST': 'localhost',
        'PORT': '',

Let’s quickly go over the settings,

DATABASES – This constant is a dictionary of database connection information and is required by Django. You can have multiple connections to different databases, but most of the time, you will just need an entry called default.

default – This is the default database connection configuration. You should always have a default set of connections settings.

'ENGINE': 'django.db.backends.postgresql_psycopg2' – This tells Django to use the Postgres backend. This, in turn uses psycopg2, Python’s Postgres library which we installed earlier.

'NAME': 'mydb' – The name of the database you want to connect to.

'USER': 'myuser' – The User with access to the database.

'PASSWORD': 'mypass' – The password for your database user.

'HOST': 'localhost' – The address of the database server you want to connect to.

'PORT': '' – The port you want to connect to, which by default is ‘5432’

Test The Database Connection

After updating the database configurations, it’s time to test the connection. The Django database migration process ensures all Django project logic associated with a database is reflected in the database itself.

During the first migration against the database, there are a series of migrations Django requires that create tables to keep track of administrators and sessions.

In the directory where script exists, run the following command.

python migrate

If everything went right you should see an output like this.

Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying sessions.0001_initial... OK

Furthermore, you can now create a superuser and login to the admin dashboard.

Support Django Central

If you appreciate my work, or if it has helped you along your journey. It would mean a lot to me if you could write a message on my wall and share a cup of coffee (or tea) with me.
Buy Me a Coffee at

21 thoughts on “Using PostgreSQL with Django”

  1. Hi There,
    I keep getting a super long error message when I try to enter $ pip install psycopg2 command.

    Then someone on the internet said to use, $ pip install psycopg2-binary. I didn’t get any error messages but I still can’t get the next command to work $ sudo -u postgres psql.

    Do you have any suggestions?

    • pip install psycopg2-binary, this is the latest v. of that work effectively with python 3 and above till we are told it’s out of market/ simply not matching well with other softwares.
      also, ensure to be at the same level with manage .py and make sure to use the correct login details. remember not the old username and password, but the latest that you used, not unless you skipped to use the proposed name by the vs code, but now with a password of your choice.

  2. Hi,
    I try to run the command “sudo -u postgres psql”
    but I get an error: ” ‘sudo’ is not recognized as an internal or external command, operable program or batch file. ”

    what I do wrong?

  3. Hello, great article!
    quick question: I was running a SQLite db and now I am trying to switch to use PostgreSQL, but I get this error that I cannot seem to find any information about online:

    django.db.utils.ProgrammingError: cannot cast type numeric to interval
    LINE 1: …R COLUMN “duration” TYPE interval USING “duration”::interval

    Is this something you’ve seen before? Any hints on how to solve?

  4. Having trouble seeing the blog posts on index page. Shows up in admin page just not sure why PostgreSQL database isn’t showing. I have one entry as a test. Any help would be appreciated.

  5. This one is a well-organized blog on PostgreSQL installation and connecting to Django, came here after a lot of googling, but that will surely my last blog on this part.


Leave a Comment