CRUD Operations in Django 3 With Example

All we knew, CRUD operations in Django 3 are the most common things in Every Django project. Let’s start this Common Django CRUD operations with a Client details application.

What is CRUD ?

CRUD means,

C – Create , R – Read , U – Update , D – Delete

Most of the Django projects have these common operations in some form. To Create a Django Application follow this link.

Read Here : How to Create Django Project

Note:

I created a Django project with the name of crud_exp and my app name is crud.

How to use CRUD operations in Django

In this Django project, we will add our client info, we will show our client info, we will update the client info and finally we will delete our client info.

This is the overall picture of our Client info application.

Django CRUD Operations with Example

Here, I gave all the URLs regarding the Client details crud operations project.

urls.py

from django.urls import path 
from .views import home,add_client,edit_client,delete_client



urlpatterns = [
    path('',home,name='home'),
    path('add/',add_client,name='add'),
    path('edit/<int:id>/',edit_client,name='edit'),
    path('delete/<int:id>/',delete_client,name='delete'),
]

Here, we imported home, add_client, edit_client, delete_client from views.py.

views.py

Here, we created views for Read ( home) , add_client, edit_client and delete_client .

home view used for read operation. It will get the all objects or client list from our model.

add_client view used for adding the client to our model.

edit_client view used for updating the client info in our model.

delete_client view used for delete the client info in our model.

we used redirect() method to redirect the URLs after our CRUD operations.

id used for identifying the client in our model.

Here is the views.py file,

from django.shortcuts import render,redirect

# Create your views here.
from .models import ClientInfo


def home(request): # READ

    all_clients = ClientInfo.objects.all()

    context ={
        'all_clients':all_clients,
        
        }
    return render(request,'index.html',context)


def add_client(request): # CREATE

    if request.method == 'POST':
        name = request.POST.get('name')
        email = request.POST.get('email')
        phone = request.POST.get('phone')
        status = request.POST.get('status')

        #print(10*'---',name,email,phone,status)

        client = ClientInfo(name=name,email=email,phone=phone,status=status)
        client.save()
        return redirect('home')


    return render(request,'index.html')


def delete_client(request,id): #DELETE

    client = ClientInfo.objects.get(id=id)
    client.delete()
    return redirect('home')

    r#eturn render(request,'index.html')


def edit_client(request,id): #UPDATE
    if request.method == 'POST':
        name = request.POST.get('name')
        email = request.POST.get('email')
        phone = request.POST.get('phone')
        status = request.POST.get('status')

        #print(10*'---',name,email,phone,status)

        client = ClientInfo.objects.get(id=id)

        client.name = name
        client.email = email
        client.phone = phone
        client.status = status
        client.save()
        
        return redirect('home')

    else:
        client = ClientInfo.objects.get(id=id)
        context = {
            'client':client,
        }
        return render(request,'edit.html',context)


Models.py

we have to create a model which stores the information of our client. Here I created 4 fields like name, email, phone, status. You can add more fields if you need.

from django.db import models

# Create your models here.



class ClientInfo(models.Model):
    name  = models.CharField(max_length=20)
    email = models.EmailField(max_length=254)
    phone = models.CharField(max_length=10)
    status = models.BooleanField(default=True)

    

    class Meta:
        verbose_name = ("ClientInfo")
        verbose_name_plural = ("ClientInfo")

    def __str__(self):
        return self.name



Templates

We need to create templates to show our client info, add, delete and update client info. You need to configure the templates , If you don’t know get the knowledge here – Django Template settings

I am giving 2 templates here, one is index.html and edit.html. These templates were already configured in our views.py, please make sure your html files and configured files views.py must be same.

index.html

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">

    <title>Crud - Client Info</title>
 
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<!------ Include the above in your HEAD tag ---------->
</head>
<body>

<div class="container">
	<div class="row">
	    
	    
<link href="http://fontawesome.io/assets/font-awesome/css/font-awesome.css" rel="stylesheet" media="screen">
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" type="text/css" rel="stylesheet">



<!-- FORM  -->	    
<div class="col-md-12">
	       
<form class="form-horizontal" id="form-edit-client" method='POST' action='{% url 'add' %}'> {% csrf_token %}
<fieldset>

<!-- Form Name -->
<legend class="bg-success" style="text-align:center; color:white;">Client Details CRUD Operations</legend>

<!-- Text input-->
<div class="form-group">
  <label class="col-md-4 control-label" for="client-name" name="name" required>Name</label>  
  <div class="col-md-4">
  <input id="client-name" name="name" type="text" placeholder="your client's name" class="form-control input-md">
  <span class="help-block">Full name of your client</span>  
  </div>
</div>

<!-- Prepended text-->
<div class="form-group">
  <label class="col-md-4 control-label" for="client-email" name="email" required>Email</label>
  <div class="col-md-4">
    <div class="input-group">
      <span class="input-group-addon">@</span>
      <input id="client-email" name="email" class="form-control" placeholder="yourname@yourdomain.com" type="text">
    </div>
    <p class="help-block">Email of your client</p>
  </div>
</div>



<!-- Form Phone -->
<div class="form-group">
  <label class="col-md-4 control-label" for="client-name" name="phone" required>Phone</label>  
  <div class="col-md-4">
  <input id="client-name" name="phone" type="text" placeholder="your client's Phone" class="form-control input-md">
  <span class="help-block">Phone of your client</span>  
  </div>
</div>


<!-- Multiple Radios -->
<div class="form-group">
  <label class="col-md-4 control-label" for="client-status" name="status" required>Client status</label>
  <div class="col-md-4">
  <div class="radio">
    <label for="client-status-0">
      <input type="radio" name="status"  id="client-status-0" value="True" checked="checked">
      Active
    </label>
	</div>
  <div class="radio">
    <label for="client-status-1">
      <input type="radio" name="status" id="client-status-1" value="False">
      Inactive
    </label>
	</div>
  </div>
</div>


<!-- Button -->
<div class="form-group">
  <label class="col-md-4 control-label" for="btn-save"></label>
  <div class="col-md-4">
    <button id="btn-save" class="btn btn-success" type="submit">Save</button>
  </div>
</div>

</fieldset>
</form>
</div> 
	    



<!-- LIST -->
<div class=col-md-12>
    
    <form id="form-list-client">
            <legend>List of clients</legend>
     
    <!-- 
    <div class="pull-right">
        <a class="btn btn-default-btn-xs btn-primary"><i class="glyphicon glyphicon-refresh"></i> Refresh</a>
        <a class="btn btn-default-btn-xs btn-success"><i class="glyphicon glyphicon-plus"></i> New</a>
    </div> -->

    <table class="table table-bordered table-condensed table-hover">
        <thead>
            <tr>
                <td>Name</td>
                <th>Email</th>
                <th>Phone</th>
                <th>Status</th>
                <th>Actions</th>
            </tr>
                
        </thead>

        <tbody id="form-list-client-body">
        {% for client in all_clients  %}
        
        
            <tr>
                <td>{{client.name}}</td>
                <td>{{client.email}}</td>
                <td>{{client.phone}}</td>
                {% if client.status %}
                <td>Active</td>
                
                {% else %}
                <td>Inactive</td>
                {% endif %}
                
                <td>
                    
                    <a href='/edit/{{client.id}}/' title="edit this user" class="btn btn-default btn-sm "> <i class="glyphicon glyphicon-edit text-primary"></i> </a>
                    <a href='/delete/{{client.id}}/' title="delete this user" class="btn btn-default btn-sm "> <i class="glyphicon glyphicon-trash text-danger"></i> </a>  
                </td>
            </tr>

            {% endfor %}
            
        </tbody>


    </table>
    </form>    
</div>
</div>
<body>
</html>

And here is the edit.html file which helps to update our client info.

edit.html

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">

    <title>Crud - Client Info</title>
 



<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<!------ Include the above in your HEAD tag ---------->
</head>
<body>

<div class="container">
	<div class="row">
	    
	    
<link href="http://fontawesome.io/assets/font-awesome/css/font-awesome.css" rel="stylesheet" media="screen">
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" type="text/css" rel="stylesheet">



<!-- FORM  -->	    
<div class="col-md-12">
	       
<form class="form-horizontal" id="form-edit-client" method='POST' action=''> {% csrf_token %}
<fieldset>

<!-- Form Name -->
<legend class="bg-success" style="text-align:center; color:white;">Client Details - Update</legend>

<!-- Text input-->
<div class="form-group">
  <label class="col-md-4 control-label" for="client-name" name="name" required>Name</label>  
  <div class="col-md-4">
  <input id="client-name" name="name" type="text" value="{{client.name}}" class="form-control input-md">
  <span class="help-block">Full name of your client</span>  
  </div>
</div>

<!-- Prepended text-->
<div class="form-group">
  <label class="col-md-4 control-label" for="client-email" name="email" required>Email</label>
  <div class="col-md-4">
    <div class="input-group">
      <span class="input-group-addon">@</span>
      <input id="client-email" name="email" class="form-control" value="{{client.email}}"" type="text">
    </div>
    <p class="help-block">Email of your client</p>
  </div>
</div>



<!-- Form Phone -->
<div class="form-group">
  <label class="col-md-4 control-label" for="client-name" name="phone" required>Phone</label>  
  <div class="col-md-4">
  <input id="client-name" name="phone" type="text" value="{{client.phone}}"" class="form-control input-md">
  <span class="help-block">Phone of your client</span>  
  </div>
</div>


<!-- Multiple Radios -->
<div class="form-group">
  <label class="col-md-4 control-label" for="client-status" name="status" required>Client status</label>
  <div class="col-md-4">
  {% if client.status %}
  <div class="radio">
    <label for="client-status-0">
      <input type="radio" name="status"  id="client-status-0" value="True" checked="checked">
      Active
    </label>
	</div>

    <div class="radio">
    <label for="client-status-1">
      <input type="radio" name="status" id="client-status-1" value="False">
      Inactive
    </label>
	</div>
  
  {% else %}
  <div class="radio">
    <label for="client-status-0">
      <input type="radio" name="status"  id="client-status-0" value="True">
      Active
    </label>
	</div>
  <div class="radio">
    <label for="client-status-1">
      <input type="radio" name="status" id="client-status-1" value="False" checked="checked">
      Inactive
    </label>
	</div>
  {% endif %}
  
  
  </div>
</div>


<!-- Button -->
<div class="form-group">
  <label class="col-md-4 control-label" for="btn-save"></label>
  <div class="col-md-4">
    <button id="btn-save" class="btn btn-success" type="submit">Save</button>
  </div>
</div>

</fieldset>
</form>
</div> 
	    
</body>
</html>

I hope you will completed this django crud operations successfully without any erros. let me know in the comment section if you face any problems here, or expecting more from us.

Always thanks for the patience and visit. Good to see you.

Thanks & Cheers !

Check out our YouTube Channel Jp NaN

Leave a Reply