Django CRUD Example with PostgreSQL

In this Python Django Tutorial, I will show you the Django CRUD example with PostgreSQL, here you will understand how to perform CRUD operations with the PostgreSQL database.

I will explain to you the concept behind CRUD operation, and then you learn about this concept by building a Django project that is based on the employee. Where you will create, view, update, and delete the specific employee from the database.

Django PostgreSQL CRUD

CRUD operation provides the required tools to manipulate data in the system that allows user to do the following things according to the requirement:

  • Create: In a database table, create or add new entries.
  • Retrieve: Read, Retrieve, or Fetch all or some entries from the table in a database.
  • Update: In a database table, update or amend existing entries.
  • Delete: In a database table, delete existing records.

Without the CRUD operation, a system or website becomes static or non-interactive, so when CRUD operation is implemented, it makes the website dynamic and user-friendly.

  • When CRUD operations are implemented in an optimized way, then it retrieves or manipulates the data in a more efficient way that improves the system or website performance.
  • CRUD operation provides integrity when it is implemented in a proper manner that makes sure user data remains consistent.

To perform CRUD operations using PostgreSQL, we have to install the pgAdmin Management Tool, you can download the tool by clicking on PostgreSQL.

Django CRUD Project setup with PostgreSQL

In this section, you will learn to set up a Django project to perform CRUD operations with PostgreSQL.

CREATE VIRTUAL ENVIRONMENT: Open the command prompt and type the below command to create a virtual environment named ‘env’.

python -m venv env

Activate the environment ‘env’ using the below code.

env\Scripts\activate

After activating the environment, install the latest version of Django.

pip install Django

CREATE PROJECT: Now, create a Django project named ‘Employee’. For this, type the following command in the terminal.

django-admin startproject Employee

Change the directory of the Django project ’employee’ using the below code.

cd employee

CREATE APP: In that folder, create a Django app named ‘crud_app’ as part of the project. And, to make an app, run the following command in the terminal.

python manage.py startapp crud_app
Django CRUD Project setup with PostgreSQL

CREATE TEMPLATES: Then create a Templates folder in your Django app ‘crud_app’ and also create the following empty HTML files related to the CRUD operations that will be used later.

  • show.html: To display the fetched data.
  • insert.html: To add a new employee.
  • edit.html: To update the existing employee.
  • delete.html: To remove an employee entity.
Django CRUD Project setup with PostgreSQL Templates

INSTALL APP: Next, open the settings.py file of your Django project ’employee’, and add the Django app ‘crud_app’ in the INSTALLED_APPS section of the settings.py file.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'crud_app'
]
Django CRUD Project setup with PostgreSQL Installing App

DATABASE SETUP: Then connect your Django project to the PostgreSQL database so for open the settings.py file of your Django project ’employee’ and add the following configuration details.

DATABASES = {  
    'default': {  
        'ENGINE': 'django.db.backends.postgresql',  
        'NAME': 'Employee',  
        'USER':'postgres',  
        'PASSWORD':'12345',  
        'HOST':'localhost',  
        'PORT':'5432'  
    }  
}  
Django CRUD Project setup with PostgreSQL Database

Make sure to create an empty database named ’employee’ in your PostgreSQL server.

Read: Union operation on models Django

Django CRUD Create URL Pattern with PostgreSQL

In this section, you will learn to create URL patterns to connect to a specific view, and that view is called whenever a user visits the specific URL.

PROJECT URL: First set up the Django project-level URL pattern, and for that open the urls.py file of your Django project ’employee’ and add the following lines of code.

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('CRUDAPP.urls')),
]
Django CRUD Create Project URL Pattern with PostgreSQL
  • Here include the path of crud_app.urls by adding it to the urls.py file of project ’employee’.

APP URL:  Also set the app level URL pattern, that creates a new file called urls.py in your Django app ‘crud_app’ and in that file add the following path.

from django.urls import path
from . import views

urlpatterns = [
    path('', views.insert_emp, name='insert-emp'),
    path('show/', views.show_emp, name='show-emp'),
    path('edit/<int:pk>', views.edit_emp, name='edit-emp'),
    path('remove/<int:pk>', views.remove_emp, name='remove-emp'),
]
Django CRUD Create App URL Pattern with PostgreSQL

In the above code, define the URL patterns that contain the URL path and each URL path contains the URL and the corresponding view.

  • Below is the purpose of each view that is mapped to a different URL path:
    • insert_emp: To insert employee details and this view is called when the user hits the URL path ‘show/’.
    • show_emp: To show employee’s details and this view is called when the user hits the URL path ‘ ‘.
    • edit_emp: To update existing details of an employee and this view is called when the user hits the URL path ‘edit/<int:pk>’ with pk (which represents the Id).
    • remove_emp: To delete existing employees this view is called when the user hits the URL path ‘remove/<int:pk>’.

Read: Add Google reCAPTCHA to Django Form

Django CRUD Create Model with PostgreSQL

Now create a model named ‘Employee’ that represents the database table schema. After migration, the table named ’employee’ will be created in your PostgreSQL database. This table will contain the details of all the employees.

CREATE MODEL: Open the models.py file of your Django app ‘crud_app’ and in that file add the following lines of code.

from django.db import models

class Employee(models.Model):
    EmpId = models.CharField(max_length=3)
    EmpName = models.CharField(max_length=200)
    EmpGender = models.CharField(max_length=10)
    EmpEmail = models.EmailField()
    EmpDesignation = models.CharField(max_length=150)
    class Meta:
        db_table="Employee"
Django CRUD Create Model with PostgreSQL

In the above code define the model ‘Employee’ with the field list EmpId, EmpName, EmpGender, EmpEmail, and EmpDesignation of type CharField.

Read: ModuleNotFoundError: No module named Django

Register the model ‘Employee’ in the admin.py file of your Django app ‘crud_app’ using the below lines of code.

from django.contrib import admin
from .models import Employee

admin.site.register(Employee)
Django CRUD Model Register with PostgreSQL

In the above code register the Employee model on the admin site using admin.site.register() function with model name.

Django CRUD Create Views with PostgreSQL

Now create the views that you have specified in the urls.py file of your Django app ‘crud_app’. So to create a view there is a file called views.py in your Django app.

insert_emp VIEW: Add the following code in the views.py file.

from django.shortcuts import render, redirect
from .models import Employee

# Create Employee

def insert_emp(request):
    if request.method == "POST":
        EmpId = request.POST['EmpId']
        EmpName = request.POST['EmpName']
        EmpGender = request.POST['EmpGender']
        EmpEmail = request.POST['EmpEmail']
        EmpDesignation = request.POST['EmpDesignation']
        data = Employee(EmpId=EmpId, EmpName=EmpName, EmpGender=EmpGender, EmpEmail=EmpEmail, EmpDesignation= EmpDesignation)
        data.save()
  
        return redirect('show/')
    else:
        return render(request, 'insert.html')
Django CRUD Insert View with PostgreSQL

In the above code, line 6 defines the view named ‘insert_emp’ that accepts the request parameter.

Then the code (if request.method == “POST”) checks if the incoming request is a POST HTTP method. If the incoming request is the POST method, then the following things are done:

  • First values are retrieved from the parameters EmpId, EmpName, EmpGender, EmpEmail, and EmpDesign using the request.POST[‘parameter_name’] and saved in the corresponding variable.
  • The new employee record is created by passing all the values to the model Employee() and the instance of that employee is stored in the variable data.
  • To save the record in the database, a method save() is called on the data.
  • After saving the employee record a user is redirected to the URL ‘show/’

If the incoming request is not POTS, then the template ‘insert.html’ is rendered to the user.

Read: Login system in Python Django

If you remember, you created the insert.html empty file in the templates folder of your Django app ‘crud_app’.

insert HTML: Add the following lines of code in the insert.html file.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Enter Employee</title>
</head>
<style>
    table {
        border: 8px outset;
        border-radius: 10px;
        border-spacing: 10px;
        padding: 20px;
        margin-left: auto;
        margin-right: auto;
    }

    th,
    td {
        padding: 5px;
    }
</style>

<body>
    <h2 style="text-align:center"> Enter Details of Employee </h2>
    <form method="POST">
        {% csrf_token %}
        <table style="width:50%" align="center">
            <tr>
                <td>Employee Id</td>
                <td><input type="text" placeholder="Enter Employee Id" name="EmpId" </td>
            </tr>
            <tr>
                <td>Employee Name</td>
                <td><input type="text" placeholder="Enter Employee Name" name="EmpName" </td>
            </tr>
            <tr>
                <td>Gender</td>
                <td><input type="radio" name="EmpGender" value="Male"> Male
                    <input type="radio" name="EmpGender" value="Female"> Female
                    <input type="radio" name="EmpGender" value="Other"> Other
                </td>
            </tr>
            <tr>
                <td>Email</td>
                <td><input type="email" placeholder="Enter Employee Email" name="EmpEmail" </td>
            </tr>
            <tr>
                <td>Designation</td>
                <td><select name="EmpDesignation">
                        <option selected disabled=true>Select Designation</option>
                        <option> Project Manager </option>
                        <option> Programmer </option>
                        <option> Desktop Support Technician </option>
                        <option> Web Developer </option>
                        <option> Financial Advisor </option>
                        </option>
                    </select></td>
            </tr>
            <tr>
                <td colspan="2" align="center"><input type="submit" class="btn btn-success"> </td>
            </tr>
        </table>

        <br><br>
        <div class="alert alert-danger" role="alert">
            Do you want see Information of Employees?
        </div>

        <p>
            <a href="{% url 'show-emp' %}">Go To Employee Information--></a>
        </p>
    </form>
</body>

</html>
Django CRUD Insert Template with PostgreSQL

In the above code, the form element is used to build an HTML form for user input. The method=POST attribute is also added to the form tag, then, to safeguard our form from cyber-attacks {% csrf_token %} is used.

The form will look like this.

django crud insert html page with postgresql

Read: Python Django get enum choices

Next, create a view named show_emp that shows the information of all the employees added by the user.

show_emp VIEW: Add the following code in the views.py file.

from django.shortcuts import render, redirect
from .models import Employee

# Retrive Employee
        
def show_emp(request):
    employees = Employee.objects.all()
    return render(request,'show.html',{'employees':employees} )
Django CRUD Show View with PostgreSQL

At line 26 define the view show_emp that accepts the request as a parameter and then at line 27 retrieve all the employee’s data from the database using Employee.objects.all(). Finally, the user is redirected to the show.html page via this function at line 28.

Read: Python Django round to two decimal places

After creating a view show_emp, you also created the show.html template that shows the list of employees added by the user.

show HTML: Add the following code in the show.html file that exists under the directory templates of your Django app ‘crud_app’.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Search Employee</title>
</head>
<style>
    table {
        border: 8px outset;
        border-radius: 10px;
        border-spacing: 10px;
        padding: 20px;
        margin-left: auto;
        margin-right: auto;
    }

    th,
    td {
        padding: 5px;
        border: 1px solid;
    }
</style>

<body>
    <h2 style="text-align:center"> Employee Information </h2>
    <table align="center" style="margin: 0px auto;">
        <thead>
            <tr>
                <th>Employee ID</th>
                <th>Name</th>
                <th>Gender</th>
                <th>Email</th>
                <th>Designation</th>
                <th>Edit</th>
                <th>Delete</th>
            </tr>
        </thead>
        <tbody>
            {% for employee in employees %}
            <tr>
                <td>{{employee.EmpId}}</td>
                <td>{{employee.EmpName}}</td>
                <td>{{employee.EmpGender}}</td>
                <td>{{employee.EmpEmail}}</td>
                <td>{{employee.EmpDesignation}}</td>
                <td>
                    <a href="/edit/{{employee.pk}}">Update</a>
                </td>
                <td>
                    <a href="/remove/{{employee.pk}}">Delete</a>
                </td>
            </tr>
            {% endfor %}
        </tbody>
    </table>

    <br><br>
    <div class="alert alert-danger" role="alert">
        Do you want to enter more Employees?
    </div>

    <p>
        <a href="{% url 'insert-emp' %}"><-- Go To Home Page</a>
    </p>
</body>

</html>
Django CRUD Show Template with PostgreSQL

The above code displays a list of all the employees that users have entered. This template shows the table that contains the information about each employee.

  • The following are the table’s headers:
    • Emp Id: Displays the employee ID.
    • Emp Name: Display the name of the employee.
    • Emp Gender: Display the employee’s Gender.
    • Emp Email: Display the email of the employee.
    • Emp Designation: Display the occupation of the employee.
  • The following action buttons are also added to perform certain actions:
    • Update: To make changes to a specific entry that has been added by users.
    • Delete: To remove a specific employee-added entry.
django crud show html page with postgresql

Read: Python Django vs ReactJS

After that, you need to add the view logic that updates the employee details, so open the views.py file that exists in your Django app ‘crud_app’.

edit_emp VIEW: Add the following code in the views.py file.

# Update Employee

def edit_emp(request,pk):
    employees = Employee.objects.get(id=pk)
    if request.method == 'POST':
            print(request.POST)
            employees.EmpName = request.POST['EmpName']
            employees.EmpGender = request.POST['EmpGender']
            employees.EmpEmail = request.POST['EmpEmail']
            employees.EmpDesignation = request.POST['EmpDesignation']
            employees.EmpDesignation = request.POST['EmpDesignation']
            employees.save()   
            return redirect('/show')
    context = {
        'employees': employees,
    }

    return render(request,'edit.html',context)
Django CRUD Edit View with PostgreSQL

In the above code, line 35 defines the view named ‘edit_emp’ that accepts two parameters a request and pk (which is the primary key or the ID).

Read: Create form with Django Crispy Forms

Again you need to add the template coding that will allow the user to update the employee details, so open the edit.html file.

edit HTML: Add the following code in the edit.html file.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Update Employee</title>
    <style>
        table {
            border: 8px outset;
            border-radius: 10px;
            border-spacing: 10px;
            padding: 20px;
            margin-left: auto;
            margin-right: auto;
        }

        th,
        td {
            padding: 5px;
        }
    </style>
</head>

<body>
    <h2 style="text-align:center"> Update Details of Employee </h2>
    <form method="POST">
        {% csrf_token %}
        <table style="width:50%" align="center">
            <tr>
                <td>Employee Id</td>
                <td><input type="text" value="{{ employees.EmpId }}" name="EmpId"></td>
            </tr> 
            <tr>
                <td>Employee Name</td>
                <td><input type="text" value="{{ employees.EmpName }}" name="EmpName"></td>
            </tr>
            <tr>
                <td>Gender</td>
                <td><input type="text" value="{{ employees.EmpGender }}" name="EmpGender"></td>
            </tr>
            <tr>
                <td>Email</td>
                <td><input type="email" value="{{ employees.EmpEmail }}" name="EmpEmail"></td>
            </tr>
            <tr>
                <td>Designation</td>
                <td><input type="text" value="{{ employees.EmpDesignation }}" name="EmpDesignation"></td>
            </tr>
            <tr>
                <td colspan="2" align="center"><input type="submit" class="btn btn-success"></td>
            </tr>
        </table>
    </form>
</body>

</html>
Django CRUD Edit Template with PostgreSQL

The above code template shows the form that allows the user to update the specific employee details or information.

Read: Python Django set timezone

Finally, create a view named remove_emp that allows users to remove a specific employee from the database.

remove_emp VIEW: Add the following code in the views.py file.

def remove_emp(request, pk):
    employees = Employee.objects.get(id=pk)

    if request.method == 'POST':
        employees.delete()
        return redirect('/show')

    context = {
        'employees': employees,
    }

    return render(request, 'delete.html', context)
Django CRUD Remove View with PostgreSQL

In the above code retrieving the specific employee from the database based on the provided ID (pk) and then calling the method delete() on the employee’s object.

Also, add the template code in your delete.html file where the user can perform a delete operation to remove a specific user from the database.

delete HTML: Add the following code in the delete.html file.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Delete Employee</title>
</head>

<body>
    <form action="" method="POST">
        {% csrf_token %}

        <br><br>
        <div class="alert alert-danger" role="alert">
            Are you sure you want to delete "{{ employees.EmpName}}"?
        </div>

        <p>
            <a href="{% url 'show-emp' %}"><-- Return</a>
        </p>

        <p>
            <input class="btn btn-danger" type="submit" value="Confirm">
        </p>
    </form>
</body>

</html>
Django CRUD Remove Template with PostgreSQL

In the above code, the template delete.html shows the employee that you want to delete or a list of employees and then you can choose which employee to delete from the database.

  • When you click on the Return Button, you are redirected to the previous page, which is the search template.

Read: Python Django format date

Django CRUD with PostgreSQL Migrations and Running Server

Now it is time to migrate the default models that come with Django and the model that you have created for the employee.

But before migration, you need to install a package psycopg2 so open the terminal and run the below command.

pip install psycopg2
Django CRUD with PostgreSQL Installing psycopg2

Now run the below command to make a migration file.

python manage.py makemigartions

After that, run the migrate command executes the instructions given in the migrations file.

python manage.py migrate
Django CRUD with PostgreSQL Migrations

Run Server: To run the development server run the following command in your terminal.

python manage.py runserver
Django CRUD with PostgreSQL Running Server

Read: How to create Contact Form with Django and SQLite

Now open your browser and go to the URL ‘http://127.0.0.1:8000/’, and you see the page as shown below.

django crud insert view with postgresql

Firstly, enter the details of the employee. If you click on Go To Employee Information, it redirects to Employee Information.

As soon as you click on the Submit Button, it redirects to the Employee Information page where you see all the employees that you have added.

django crud show view with postgresql

If you click on the Go To Home Page link, it redirects to the page where you can enter employee details.

Let’s update the details of the employee with the ID equal to 100 that you have added

Django CRUD with PostgreSQL Update Employee

Here, update the email from ebowyera@plala.or.ip to ebowyera@gmail.com

Django CRUD with PostgreSQL Updated Employee

When you click on the Submit Button, it will redirect to the Employee Information Page.

From, here we see that the email is updated.

Django CRUD with PostgreSQL Updated Employee Email

Now delete the employee with an ID equal to 100 and see what will happen. So click on the Delete button.

Django CRUD with PostgreSQL Delete Employee

Then click on the Confirm button to delete the employee ‘Earl Bowyer’.

From, here we see that employee Lyneett Cluse successfully deleted.

Django CRUD with PostgreSQL Deleted Employee

Conclusion

In this Python Django Tutorial, you learned about the Django CRUD example with PostgreSQL and also the importance of the CRUD operations, you built the Django project based on the employee where you created, viewed, updated, and deleted the employee from the database.

You may also like to read.