The Django Tutorial and PostgreSQL database

Introduction

Django is a fast, high level developmental framework that allows for developing a web application in Python with a lot less hassle than some other frameworks. While Django automatically stores data in a SQLite database, this Django tutorial for postgresql will explain how to store data in Python with the Django framework using the PostgreSQL database cluster.

Prerequisites

  • It must be confirmed whether the PostgreSQL database is installed on the local machine, as it will require the credentials that will be set to the Django application. Execute the sudo systemctl status postgresql command in a Systemd distro of Linux terminal to confirm the system is running, or just use the pg_ctl status command.

  • For MacOS, start the Homebrew PostgreSQL service with the brew services start postgresql command and then execute the brew info postgres command.

  • Python must be installed and working properly. Python 3 is recommended as Python 2.7 is being deprecated and losing support.

Enter the psql console

Execute the following command to enter the interactive PostgreSQL terminal that corresponds to the access of the PostgreSQL administrative user:

1
sudo su - postgres

Now enter the sudo password or the root authentication for the device and press the -kbd-ENTER-/kbd- key.

When inside the PostgreSQL shell session, execute the following command to enter the console:

1
psql

Create database and user

After entering the psql command-line console, a database and user must be created that can be set for the Django application. Execute the following command to create the database:

1
CREATE DATABASE djangodb;

Now execute the following command to create a user login and password that will grant privileges to the newly created database:

1
CREATE USER orkb WITH PASSWORD 'mypass123';

Next, modify the parameters for the connection to the Django framework. This is needed to set up the operations for the value queries when a connection is established.

Execute the following ALTER ROLE SQL statement to modify the parameters:

1
ALTER ROLE orkb SET client_encoding TO 'utf-8';

NOTE: This operation will set the encoding to UTF-8, the default expected in Django framework.

Execute the following command to the default transaction isolation:

1
ALTER ROLE orkb SET default_transaction_isolation TO 'read committed';

NOTE: This will set the default transaction isolation each time access is granted to make a query that avoids the transactions that are not committed.

Execute the following command to set the timezone:

1
ALTER ROLE orkb SET timezone TO 'UTC';

NOTE: Django typically uses the UTC, by default, for the timezone.

Finally, execute the following command to grant the user access privileges to the database:

1
GRANT ALL PRIVILEGES ON DATABASE djangodb TO orkb;

The results should resemble the following image:

Django Tutorial PostgreSQL creating database in psql and altering role

Install Django in Virtual Environment

A virtual environment is used to manage the dependencies of different projects by creating a separation of Python isolation to the virtual environments.

Using the terminal, execute the following command to create a directory in the Django framework to store the project:

1
mkdir ~/orkb
1
cd ~/orkb

Now execute the following command to create a virtual environment that will store the Django project in Python.

1
virtualenv venv

NOTE: The venv command is now a built-in feature of Python since version 3.6. If using a Python version older than 3.6, the virtual environment package for Python must be installed and activated before installing the Django framework.

Execute the following command to activate the virtual environment:

1
source venv/bin/activate

With the venv activated, install the Django framework using the following pip3 command:

1
pip3 install Django

Now execute the following command to install the psycopg2 to allow configuring of PostgreSQL:

1
pip3 install psycopg2

Start the Django project

Using the below command will allow for creating a folder to hold the codes within the project directory. Note that the manage.py is created after putting a dot at the end of the command to set the project correctly.

Execute the following command to start the Django project:

1
django-admin startproject orkb .

With the project now created, execute the following command to configure the project to set the PostgreSQL database credentials:

1
nano venv/settings.py

Look for the default configured database as SQLite and set it for the database credentials in PostgreSQL as follows:

1
2
3
4
5
6
7
8
9
10
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'djangoproject',
        'USER': 'orkb',
        'PASSWORD': 'mypass123',
        'HOST': 'localhost',
        'PORT': '',
    }
}

Change the ALLOWED_HOSTS Python list of allowable domains, as shown below, and add the domain’s IP address or localhost for local development:

1
ALLOWED_HOSTS = ['localhost', '127.0.0.1']

The results should resemble the following:

Screenshot of Django tutorial PostgreSQL changing settings for the Django project

Test the Django application

With the configuration finished, the structures of data must be migrated to the database to test the application for the Django server.

Execute the following command to access the project directory:

1
cd ~/orkb

Now add the following code to create a database structure:

1
python3 manage.py makemigrations
1
python3 manage.py migrate

Finally, execute the following code to create an administrative account for the Django application:

1
2
3
4
5
6
python3 manage.py createsuperuser
Username (leave blank to use 'linux'): orkb
Email address: orkb@email.com
Password:
Password (again):
Superuser created successfully.

NOTE: A current admin account can be used to set up a superuser account for the Django application.

Now execute the following command to test the Django application and confirm it is working properly:

1
python3 manage.py runserver 127.0.0.1:8000

When the system displays a message that the application is working, add /admin in the URL and enter the previously set up username and password.

Conclusion

This Django tutorial for postgresql explained how to store data in Python with the Django framework using PostgreSQL. The tutorial explained how to create a database and user, grant the user access to the database, install Django in a virtual environment and activate the virtual environment. The Django tutorial for postgresql also explained how to start the Django project, create an administrative account and finally test the Django application. Remember that the virtual environment package for Python must be installed and activated separately, before installing the Django framework, if using a version of Python prior to 3.6.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.