How To Use PostgreSQL with your Django Application on Ubuntu
Last Updated :
21 Feb, 2023
This article describes how to configure PostgreSQL with the Django application on your Ubuntu machine. First, let's look at an overview of all the tools we use.
- PostgreSQL is a high-performance, reliable, and robust open-source relational database management system (RDBMS).
- Django is a robust, free, open-source, Python-based web framework that follows the MVT (Model-Template-View) architectural pattern. It uses an SQLite database by default and It is configured to work with Django by default, but this SQLite database is not suitable for complex projects. Other databases such as Postgres can be used here as they are more robust and preferred. Now let's configure Postgres to work with our Django application,
Installing required packages
Installing Postgres on our machine is the first step in configuring it with Django. The command below will install PostgreSQL on the Ubuntu machine.
sudo apt install postgresql postgresql-contrib
Configure PostgreSQL
To interact with Postgres we need to use its interactive shell prompt which we can activate as follow.
sudo -u postgres psql
Creating a Database and User
You'll see that the question has changed; this means that we can now configure Postgres by creating a database and a user for it, along with a user and it is granted all required privileges on the created database.
# create a database named demo
CREATE DATABASE demo;
# created a user demouser with password 123456789
CREATE USER demouser WITH PASSWORD '12345678';
# configured client encoding to utf8
ALTER ROLE demouser SET client_encoding TO 'utf8';
ALTER ROLE demouser SET default_transaction_isolation TO 'read committed';
ALTER ROLE demouser SET timezone TO 'UTC';
GRANT ALL PRIVILEGES ON DATABASE demo TO demouser; # granted required access to demouser over demo db
Exit from shell
As you can see above a database is created successfully along with a user and it is granted all required privileges on the crested database. Now we are done with the Postgres setup let's exit it.
\q
Setup a Virtual Environment
Let's configure the virtual environment for development, this step can be skipped but it is always recommended to use a development environment for each project, this can be achieved using a Python virtual environment.
mkdir gfg
# Move to gfg folder
cd gfg
Here we created a dedicated folder for the project, you can name it anything you want and cd (change directory) to go into your newly created directory then run the following command that will create a virtual environment for your project.
python -m venv venv
ls
Now let’s activate the virtual environment and start using it.
# source venv/bin/activate
Installing and Creating a Django Project
Now that the development environment is configured we can start a Django project. First, we need Django to install it as follows:
python -m pip install Django
Creating Project
Let’s create a Django project by running the following commands:
django-admin startproject demo_project
The above command just created the Django default starter project, now we need to do a few tweaks in the settings.py file to allow the client access to the Django instance and also connect it with Postgres.
Configuring the Django with Postgres Database
In Django apps, the starter project is configured by default to use an SQLite database. You'll need to install a package using pip and modify the setting.py file to connect to Postgres, this is act as a connector. First, install a pip package called "psycopg2-binary'', It is a PostgreSQL database driver, it is used to perform operations on PostgreSQL using python.
pip install psycopg2-binary
Now let us make the required changes to the setting file,
nano settings.py
As the film opens, find the database section as shown:
By default, it is configured to use SQLite database as you can see. To connect it to Postgres Database make a change as follow:
Migrate all Files to the Database
Let's migrate changes to the database using the following commands.
python manage.py makemigrations
python manage.py migrate
Output:
Testing PostgreSQL Connection with Django
Your Django app is now connected to your Postgres database. For confirmation, let's can check the Django Admin panel and PostgreSQL Database:
To test the database let's create a Django superuser and check if it's working or not using the following command:
python manage.py createsuperuser
Now as the superuser is created let's use it in the Django admin panel for that visit http://127.0.0.1:8000/admin in a browser and you will be prompted to the Login, Fill in the superuser credentials.
Now, you can see all the created users in the panel:
Over here you can see all the tables created by Django in PostgreSQL.
Similar Reads
Python Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read