Support Our Site

To ensure we can continue delivering content and maintaining a free platform for all users, we kindly request that you disable your adblocker. Your contribution greatly supports our site's growth and development.

Using PostgreSQL with Django

4 min read

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.

Pre-Requirements

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 https://www.postgresql.org/download/ 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

 CREATE DATABASE mydb;

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

Creating User

 CREATE USER myuser WITH ENCRYPTED PASSWORD 'mypass';

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

 GRANT ALL PRIVILEGES ON DATABASE mydb TO myuser;

Now our user has administrative access to the database.

Now exit the SQL prompt.

\q

Integrating PostgreSQL With Django

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

DATABASES = { 
   '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.

DATABASES = {
    '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 manage.py script exists, run the following command.

python manage.py 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.


DJANGO

Latest Articles

Latest from djangocentral

How to Use Subquery() in Django With Practical Examples

In the realm of web development, Django stands as a powerful and versatile framework for building robust applications. One of the key aspects of developing efficient and optimized web applications is handling database queries effectively. In this article…
Read more →

4 min read

DRF Serializer: Handling OrderedDict and Converting It to a Dictionary or JSON

In Django Rest Framework (DRF) tests, when you access serializer.data, you might encounter an OrderedDict instead of a regular dictionary. This behavior is intentional and reflects the design of DRF's serialization process.Understanding the Problem The u…
Read more →

3 min read

Django Rest Framework CheetSheet: Mastering API Development

Django Rest Framework (DRF) is a powerful toolkit that makes building robust and scalable web APIs with Django a breeze. Whether you're a seasoned Django developer or a newcomer, having a comprehensive cheat sheet at your disposal can be a game-changer. …
Read more →

5 min read

How to Perform NOT Queries in Django ORM

In Django, performing NOT queries allows you to exclude certain records from the query results based on specific conditions. The NOT operator, represented by the tilde (~) when used in conjunction with the Django ORM's Q object, helps you construct compl…
Read more →

3 min read