Django CRUD example with PostgreSQL

In this Python Django Tutorial, we will learn Django CRUD example with PostgreSQL. And, these are the following topics that we are going to discuss in this tutorial.

  • Django PostgreSQL CRUD
  • Django CRUD project setup with PostgreSQL
  • Django CRUD create url pattern with PostgreSQL
  • Djnago CRUD create views with PostgreSQL
  • Django CRUD create model with PostgreSQL
  • Django CRUD register model with PostgreSQL
  • Django CRUD insert view function with PostgreSQL
  • Django CRUD insert HTML page with PostgreSQL
  • Django CRUD show view function with PostgreSQL
  • Django CRUD show HTML page with PostgreSQL
  • Django CRUD edit view function with PostgreSQL
  • Django CRUD edit HTML page with PostgreSQL
  • Djnago CRUD remove view function with PostgreSQL
  • Django CRUD remove HTML page with PostgreSQL
  • Django CRUD basic command with PostgreSQL
  • Django CRUD example with PostgreSQL

Django PostgreSQL CRUD

In this section, we’ll learn about CRUD operations using the PostgreSQL database.

Django is an MVT web framework architecture. By using the Django framework we can perform CRUD operations. And here CRUD stands for Create, Retrieve, Update, and Delete.

And we’ll learn about Django’s CRUD operations which are as follow.

  • Create: Users can use the create function to add a new record to the database.
  • Read: The read command is analogous to the search command. It allows users to search and read the values of specific records in the table.
  • Update: The update function is used to make changes to existing records in the database. Users may need to edit information in multiple fields to completely change a record.
  • Delete: Users can use the delete function to delete records from a database that is no longer needed.

To perform CRUD operations using PostgreSQL, we have to install the pgAdmin Management Tool.

Django CRUD project setup with PostgreSQL

In this section, we’ll learn to set up a Django project to perform CRUD operations with PostgreSQL.

CREATE PROJECT: First, we need to create a Django project. For this, type the following command in the terminal.

django-admin startproject Employee
  • Here, we create a Django project named Employee.
django crud example with postgresql
CREATE PROJECT IN DJANGO

CREATE APP: Following that, we’ll construct a CRUDAPP app as part of the project. We’ll also execute CRUD tasks later on it. And, to make an app, run the following command in the terminal.

python manage.py startapp CRUDAPP
django crud postgersql
CREATE APP IN DJANGO

CREATE TEMPLATES: The Templates folder is then created in the project root directory. And, we’ll create HTML files within the folder.

The following HTML files are created to perform CRUD operations.

  • 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.
python django crud example with postgresql
TEMPLATES FOR DJANGO PROJECT

INSTALL APP: In the settings.py file, we must include the CRUDAPP app.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'CRUDAPP'
]
python django crud postgresql
INSTALL APP IN DJANGO SETTINGS

ADD TEMPLATES: We also need to add the Templates directory in the settings.py file.

'DIRS': ['Templates']
django crud project setup with postgresql
TEMPLATES IN DJANGO SETTINGS

DATABASE SETUP: Create a PostgreSQL database called Employee and set it up in the Django project’s settings.py file.

DATABASES = {  
    'default': {  
        'ENGINE': 'django.db.backends.postgresql',  
        'NAME': 'Employee',  
        'USER':'postgres',  
        'PASSWORD':'[email protected]',  
        'HOST':'localhost',  
        'PORT':'5432'  
    }  
}  
django crud postgresql connection
DATABASE SETUP IN DJANGO

Read: Union operation on models Django

Django CRUD create url pattern with PostgreSQL

In this section, we’ll learn to create URL patterns to perform CRUD operations using PostgreSQL.

PROJECT URL: Add the following code in the project’s urls.py file.

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('CRUDAPP.urls')),
]
  • We include the path of CRUDAPP.urls by adding it into the Employee urls.py file.

APP URL:  Firstly, we have to create a file with the name urls.py in the app directory. Now, we define the path of the different views created under the views.py file of the app.

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'),
]
  • Here we create the following views:
    • insert_emp: To insert employee detail.
    • show_emp: To show employees’ details.
    • edit_emp: To update existing details of an employee.
    • remove_emp: To delete existing employee.

Djnago CRUD create views with PostgreSQL

In this section, we’ll look at the views function that we have to create in the views.py file.

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

# Create your views here.

# Create Employee...

def insert_emp(request):
    ....
    ....

# Retrieve Employees...

def show_emp(request):
    ....
    ....

# Update Employees...

def edit_emp(request):
    ....
    ....

# Delete Employees...

def remove_emp(request):
    ....
    ....
  • Here, we create the views that we’ll use to do CRUD operations with PostgreSQL.

Django CRUD create model with PostgreSQL

In this section, we’ll develop a model to execute CRUD actions.

CREATE MODEL: Add the following code inside the models.py file.

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"
  • We create Employee model with five fields.
  • The respective fields are EmpId, EmpName, EmpGender, EmpEmail, and EmpDesignation.

Read: ModuleNotFoundError: No module named Django

Django CRUD register model with PostgreSQL

In this section, we’ll register the above-created model.

REGISTER MODEL: Add the following code in the admin.py file.

from django.contrib import admin
from .models impor Employee

admin.site.register(Employee)
  • To register the Employee model on the admin site, we use the admin.site.register() function with model name.

Django CRUD insert view function with PostgreSQL

In this section, we’ll learn to create a view function to insert employee details.

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

from django.shortcuts import render, redirect
from CRUDAPP.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')
  • With the request parameter, we define the insert_emp view, which allows the user to input new employee information.
  • If you successfully enter employee details, you will be redirected to the show HTML page; otherwise, you will be redirected to the insert HTML page.

Read: Login system in Python Django

Django CRUD insert HTML page with PostgreSQL

In this section, we’ll learn to create an HTML template for adding details of new employees.

insert HTML: Add the following 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>
  • 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, we use {% csrf_token %}.
django crud insert html page with postgresql
INSERT HTML TEMPLATE EXAMPLE IN DJANGO

Read: Python Django get enum choices

Django CRUD show view function with PostgreSQL

In this section, we’ll learn to create a view function 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 CRUDAPP.models import Employee

# Retrive Employee
        
def show_emp(request):
    employees = Employee.objects.all()
    return render(request,'show.html',{'employees':employees} )
  • The show_emp view shows all of the information about the employees that users have created.
  • The user is redirected to the show.html page via this function.

Read: Python Django round to two decimal places

Django CRUD show HTML page with PostgreSQL

In this section, we’ll learn to create an HTML template that shows the list of employees added by the user.

show HTML: Add the following code in the show.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>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>
  • We’re going to make an HTML template that displays a list of all the employees that users have entered.
  • 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 Gender.
    • Emp Email: Display the email of the employee.
    • Emp Designation: Display the occupation of the employee.
  • The following action buttons are also visible:
    • 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
SHOW HTML TEMPLATE OF DJANGO PROJECT

Read: Python Django vs ReactJS

Django CRUD edit view function with PostgreSQL

In this section, we’ll learn to create a view function that updates the information of the existing employee.

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

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

# Update Employee

def edit_emp(request,pk):
    employees = Employee.objects.get(id=pk)
    if request.method == 'POST':
        return redirect('/show')

    context = {
        'employees': employees,
    }

    return render(request,'edit.html',context)
  • The edit_emp view is similar to the insert_emp view.
  • We make updates on the basis of the primary key of the employee.

Django CRUD edit HTML page with PostgreSQL

In this section, we’ll learn to develop an HTML template that updates specific employee details that users added.

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>
</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"> 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>
  • We’ll have the form here, which we’ll use to edit a specific user’s information.

Read: Python Django set timezone

Djnago CRUD remove view function with PostgreSQL

In this section, we’ll learn to create a view function that deletes the specified entry.

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

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

# Delete Employee

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)
  • remove_emp view deletes the instance from the database when someone clicks on Delete.

Django CRUD remove HTML page with PostgreSQL

In this section, we’ll learn to develop an HTML template that deletes the entry of an employee.

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>
  • We’re going to make an HTML template that deletes the precise entry that the user wishes to get rid of.
  • It also confirms one more time prior to the deletion process.
  • When we click on the Return Button, we can also go back to the previous page, which is the search template.

Read: Python Django format date

Django CRUD basic command with PostgreSQL

In this section, we’ll see some basic commands to execute CRUD operation with PostgreSQL.

Makemigrations: If the models have been modified, this command prepares a makemigrations file for our new model, or makes a new migrations file for any changes. The database modifications are not created or affected by this command.

python manage.py makemigartions
django crud basic command with postgresql
RUNNING MAKEMIGRATIONS IN DJANGO

Migrate: The migrate command executes the instructions given in the database’s recent migrations file.

python manage.py migrate
python django crud basic command with postgresql
MIGRATE COMMAND IN DJANGO

Run Server: To run the development server run the following command.

python manage.py runserver
django crud basic command using postgresql
RUNSERVER COMMAND IN DJANGO

Django CRUD example with PostgreSQL

In this section, we’ll see an example of CRUD operation with PostgreSQL.

Firstly, we have to enter the details of the employee.

django crud insert view with postgresql
Enter Detail

If we click on Go To Employee Information, we redirect to Employee Information.

When we click on Submit Button, we redirect to Employee Information.

django crud show view with postgresql
Show Information

If we click on Go To Home Page, we redirect to the page where we enter employee details.

When we click on Update see, what happens.

django crud edit with postgresql
Edit Template
django crud update with postgresql
Update Email

Here, we update the email from [email protected] to [email protected]

When we click on Submit Button, we’ll redirect to Employee Information Page.

python django crud edit postgresql
Show Employee Information in Django CRUD example with PostgreSQL

From, here we clearly see that the email id is updated.

When we click on Delete see what will happen.

django crud delete view with postgresql
DELETE TEMPLATE
django crud remove view with postgresql
Django CRUD example with PostgreSQL

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

You may also like to read the following Django tutorials.

In this Python Django Tutorial, we have discussed the Django CRUD example with PostgreSQL and we have also discussed the following topics in this tutorial.

  • Django PostgreSQL CRUD
  • Django CRUD project setup with PostgreSQL
  • Django CRUD create url pattern with PostgreSQL
  • Djnago CRUD create views with PostgreSQL
  • Django CRUD create model with PostgreSQL
  • Django CRUD register model with PostgreSQL
  • Django CRUD insert view function with PostgreSQL
  • Django CRUD insert HTML page with PostgreSQL
  • Django CRUD show view function with PostgreSQL
  • Django CRUD show HTML page with PostgreSQL
  • Django CRUD edit view function with PostgreSQL
  • Django CRUD edit HTML page with PostgreSQL
  • Djnago CRUD remove view function with PostgreSQL
  • Django CRUD remove HTML page with PostgreSQL
  • Django CRUD basic command with PostgreSQL
  • Django CRUD example with PostgreSQL