How to Setup Django With PostgreSQL on Ubuntu 20.04 – Comprehensive Guide

Django is an open-source Python framework for developing web applications. It is a versatile, powerful, efficient, and flexible framework for rapid development. Django comes with a development server which by default contains a lightweight SQLite database file to store data. Django supports major Databases like MySQL, PostgreSQL, Oracle, etc.

PostgreSQL is one of the widely used open-source Relational Database Management System (RDBMS). It has more focus on SQL standards compliance. PostgreSQL is well known for its reliability, data integrity, and correctness. It supports all major Datatypes including binary large objects, pictures, sounds, and videos.

In this Django tutorial, you’ll Download and setup Django with PostgreSQL on Ubuntu 20.04.

Prerequisites

Before you start, you’ll need the following.

  • If you do not have servers in the cloud, Create an AWS EC2 Ubuntu server instance by following the guide How to launch an EC2 Instance.
  • [Important] – Update the packages list in the server which is upgrade-able using sudo apt update
  • [Important] – Upgrade the packages in the server to the latest versions using sudo apt upgrade

Installing PostgresSQL, and Pip Package Manager

In this step, you’ll install pip and PostgreSQL from the Ubuntu repository. pip is a package manager for Python which is used to install and manage Python packages. pip connects to an online repository to get packages. Mostly Python comes with pip preinstalled.

First, Open your terminal and execute the following command (Python 3).

sudo apt-get install python3-pip python3-dev libpq-dev postgresql postgresql-contrib

You’ve installed pip package manager and PostgreSQL. These packages are the necessary Python development files required to setup Django with PostgreSQL.

PostgreSQL uses “Peer Authentication” for local connections. Peer Authentication means that if the user’s OS username is similar to the PostgreSQL username then no further authentication is required.

In the next step, you’ll create a Database and a Database user in PostgreSQL.

Creating a Database and Database User in PostgreSQL

In this step, you’ll create a database, database user, and configure the database to setup Django with PostgreSQL. In the previous step when you installed PostgreSQL, an OS user named postgres is created. The OS user postgres corresponds to the PostgreSQL administrative user postgres. Note that OS username and PostgreSQL username are the same which enables peer authentication.

First, execute the following command to log in to the PostgreSQL’s interactive session.

sudo -u postgres psql

You’ll see the below output.

Output

psql (12.5 (Ubuntu 12.5-0ubuntu0.20.04.1))
Type "help" for help.

postgres=#

You’ve now logged in to the PostgreSQL interactive session.

Next, you’ll create a database in PostgreSQL by executing the following query in the PostgreSQL interactive session. Make sure you replace db_name with a name relevant to the project.

CREATE DATABASE db_name;

You’ll see the below output.

Output

CREATE DATABASE

Now the database is created.

Make sure to end the PostgreSQL command with semicolon ( ‘;’ ).

Next, you’ll create a database user to interact with the database. Ensure you assign a strong and secure password. Execute the following query (Change the db_user and password).

 CREATE USER db_user WITH PASSWORD 'password';

You’ll see the below output.

Output

CREATE ROLE

Now the Database User is created.

You’ll configure the user to set default values for the parameters shown below.

  • encoding: utf-8
  • isolation scheme: read committed
  • timezone: UTC

By doing this, you don’t have to configure the parameters every time you make a connection in PostgreSQL database.

Next, execute the below queries to set default values for the parameters.

To set the encoding to read utf-8.

ALTER ROLE db_user SET client_encoding TO 'utf8';

You’ll see the below output.

Output

ALTER ROLE

To set the isolation to read committed.

ALTER ROLE db_user SET default_transaction_isolation TO 'read committed';

You’ll see the below output.

Output

ALTER ROLE

To set the timezone to read UTC.

ALTER ROLE db_user SET timezone TO 'UTC';

You’ll see the below output.

Output

ALTER TABLE

Next, you’ll grant database access to the newly created user by executing the below query.

GRANT ALL PRIVILEGES ON DATABASE db_name  TO db_user;

You’ll see the below output.

Output

GRANT

You’ve successfully setup the PostgreSQL by creating a database, database user and configured the database user permissions.

Finally, exit from the interactive PostgreSQL session by executing the below command.

\q

In the next step, you’ll install Django.

Installing Django Within a Python Virtual Environment

In this step, you’ll install virtualenv package, create a virtual environment, activate it, and then install django. virtualenv package helps you create virtual environments easily. Virtual environment helps to setup Django with PostgreSQL in a local scope.

First, To install virtualenv package execute the below command.

sudo pip3 install virtualenv

You’ll see the below output.

Output

Collecting virtualenv
  Downloading virtualenv-20.3.0-py2.py3-none-any.whl (5.7 MB)
     |████████████████████████████████| 5.7 MB 13.5 MB/s

Successfully installed appdirs-1.4.4 distlib-0.3.1 filelock-3.0.12 virtualenv-20.3.0

Next , you’ll create a folder for Django project by executing the below command.

mkdir ~/your_project_name

Next, move to the newly created folder by executing the below command.

cd ~/your_project_name

Next, you’ll create a Python virtual environment in your project directory (current directory) by executing the below command.

virtualenv your_environment_name

You’ll see the below output.

Output

created virtual environment CPython3.8.5.final.0-64 in 770ms
  creator CPython3Posix(dest=/home/ubuntu/first_project/first_project_env, clear=False, no_vcs_ignore=False, global=False)
  seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=/home/ubuntu/.local/share/virtualenv)
    added seed packages: pip==20.3.1, setuptools==51.0.0, wheel==0.36.1
  activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator

The virtual environment creates a local copy of Python and pip into a directory named your_environment_name inside the project directory. To use this virtual environment, First, you’ve to activate the virtual environment.

To activate the virtual environment, execute the below command.

source your_environment_name/bin/activate

You can see that the prompt is now changed to the virtual environment name.

Output

(your_environment_name) [email protected]:~/your_project_name $

Next, you’ll install Django and Psycopg2 by executing the below command. Psycopg2 is a PostgreSQL adapter for Django.

 pip install django psycopg2-binary

You’ll see the below output.

Output

Collecting django
  Downloading Django-3.1.5-py3-none-any.whl (7.8 MB)
     |████████████████████████████████| 7.8 MB 1.8 MB/s
Collecting psycopg2-binary
  Downloading psycopg2_binary-2.8.6-cp38-cp38-manylinux1_x86_64.whl (3.0 MB)
     |████████████████████████████████| 3.0 MB 44.2 MB/s

You’ve successfully installed Django and Psycopg2. Now you have the necessary files to setup Django with PostgreSQL.

Finally, you’ll start a Django project with in the your_project_name folder by executing the below command.

(your_environment_name) $ django-admin.py start_project your_project_name .

You’ve successfully installed and started a project in Django. To confirm you can see the your_project_name folder. You’ll see a new file named manage.py that is created by the Django startproject command.

In the next step, you’ll configure Django database settings to setup Django with PostgreSQL.

Configuring Database Settings to Setup Django With PostgreSQL

In this step, you’ll Setup Django with PostgreSQL by configuring the database settings in Django.

First, open the settings.py file created by Django startproject by executing the below command.

nano ~/your_project_name/your_project_name/settings.py

You’ll see a heading named Database towards the bottom of the file, scroll down to the section. You’ll see the content shown below.

...

# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases

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

...

As you can see above, currently the Django project is using default SQLite database. You’ve to change that to PostgreSQL database.

To change the database to PostgreSQL replace the Database Section with the below content.

. . .

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'your_project_name',
        'USER': 'db_user',
        'PASSWORD': 'password',
        'HOST': 'localhost',
        'PORT': '',
    }
}

. . .

Next, save and close the file by pressing CTRL + X and Y.

You’ve setup Django with PostgreSQL.

In the next step, you’ll test your setup by running a Django development server.

Testing Your Project

In this step, you’ll migrate the data structures to the PostgreSQL database and test the server. As of now, you’ve setup Django with PostgreSQL but you do not have any actual data. So, you’ll first set up the initial database structure.

First, move to the your_project_name directory.

cd ~/myproject

Next, execute the below command.

python manage.py makemigrations

Next, initiate the migrate process by executing the below command.

python manage.py migrate

You’ve created the database structure.

Next, you’ll create an administrative account by executing the below command.

python manage.py createsuperuser

You’ll be prompted to enter user name, email username, email and password. After entering the details you’ll see the below output.

Output

Username (leave blank to use 'ubuntu'): Askvikram
Email Username (leave blank to use 'ubuntu'): Askvikram
Email address: [email protected]
Password:
Password (again):
Superuser created successfully.

Next, you’ve to open a port by allowing external connections so that it can get through firewall. This can be done by executing the below command.

sudo ufw allow 8000

Next, you will start your Django development server by executing the below command.

python manage.py runserver 0.0.0.0:8000

Next, visit the browser using the IP address or Domain name of the server using port number 8000.

http://server_domain_name_or_IP_Address:8000

You’ll see the Django default root page.

Next, append “/admin” to the previous URL. You’ll be taken to the admin login page.

Finally, enter your username and password for the PostgreSQL user. You’ll be taken to the admin page. you’ve setup Django with PostgreSQL in the previous step and verified it by running a server.

Conclusion

In this article, you’ve successfully installed and configured PostgreSQL and setup Django with PostgreSQL. You’ve learned to create a superuser to access the PostgreSQL account. Though Django comes with the SQLite database for development purposes, PostgreSQL proves efficient in Production server.

What Next?

How to execute shell commands from Python?

FAQs

1. How to use Postgres database in Django?

First. ensure you have Django and PostgreSQL is installed on the server.
Next, you have to create a Django project using the startproject command inside the folder where you have to create the project.
Finally, change the settings.py file as shown in the above step, “Configuring Database Settings to Setup Django With PostgreSQL”. s

2. Why does Postgres use Django?

(i) Django offers a set of data types that will only work in PostgreSQL.
(ii) Django has django.contrib.postgres to support database operations on PostgreSQL. 
(iii) If your application makes use of storing geographical data, you will need to use PostgreSQL, as GeoDjango is only fully compatible with PostgreSQL.
(iv) Big Enterprises prefer to setup Django with PostgreSQL to support their heavy data load. Some of the companies that use PostgreSQL are Apple, Debian, Fujitsu, Red Hat, Sun Microsystem, Cisco, Skype.

3. Is Python 3.5 supported and working with PostgreSQL?

Yes, Python 3.5 can be used to setup Django with PostgreSQL. Also Django officially mentions it’s compatible with Python 3.5 and has been since version 1.8.

4. How to exit from PostgreSQL command line utility: psql

Type \q and then press ENTER to quit psql. As of PostgreSQL 11, the keywords “quit” and “exit” in the PostgreSQL command-line interface have been included to help make it easier to leave the command-line tool.

5. How to change PostgreSQL user password?

To login without a password:
sudo -u user_name psql db_name
To reset the password if you have forgotten:
ALTER USER user_name WITH PASSWORD ‘new_password’;
You can use the above command even after you’ve setup Django with PostgreSQL.

6. password authentication failed for user “postgres”

You can execute the below command to set a new password and try logging in again.
ALTER USER postgres PASSWORD ‘newPassword’;
You can visit this Stackoverflow page for detailed explanation after you’ve setup Django with PostgreSQL

Leave a Comment

Share via
Copy link
Powered by Social Snap