Table of contents
1.
Introduction
2.
Understanding CRUD Operations
3.
Getting Started
3.1.
Creating View
3.2.
Retrieve View
3.2.1.
List View
3.2.2.
Detail View
3.3.
Update View
3.4.
Delete View
4.
Frequently Ask Questions
5.
Key Takeaways
Last Updated: Mar 27, 2024

Django CRUD

Author Naman Kukreja
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

When we talk about web frameworks, there are many frameworks available, e.g., Ruby on Rail, Angular, Django, etc. So here we are going to talk about Django and its CRUD operations.

CRUD provides us with essential functions that can be used to make the work comparatively very easy. So without wasting any time, let's get started with our blog.

Understanding CRUD Operations

Django is a high-level python based web framework that allows users to quickly create web frameworks and web applications that enable rapid development of maintainable and secure websites without all of the dependency or installation problems that you usually will find with other frameworks.

Django revolves around the CRUD operations and is based on MVT architecture. Speaking generally, CRUD means Create, Retrieve, Update, Delete. Let's first get a general idea about CRUD.

  • Create - creating or adding new entries in a table in the database.
  • Retrieve - searching or reading for existing entries in the list or retrieving a particular entry from a table.
  • Update - editing or updating existing entries in the database.
  • Delete - removing or deleting entries from the table in the database.

Getting Started

In order to get started with the Django CRUD operations, first of all we’ve to create a project named codingninja and an app named ninja. 

# importing the standard Django Model
# from the built-in library

from django.db import models
 
# declare a new model with a name "NinjaModel"
class NinjaModel(models.Model):
 
#initialising the fields of a model
    title = models.CharField(max_length = 200)
    description = models.TextField()
 
   # renaming  the instances of the model
    # with their title name
    def __str__(self):
        return self.title

 

As the model has been created. Now we have to create the database, and in order to do so, we have to run two commands.

Python manage.py makemigrations
Python manage.py migrate

 

Now, we will create a Model form for this model. Creating a file forms.py in the ninja folder.

from django import forms
from .models import NinjaModel
 
 
# creating a form
class NinjaForm(forms.ModelForm):
 
    # create meta class
    Meta:
        # specify a model to be used
        model = NinjaModel
 
        # specify fields to be used
        fields = [
            "title",
            "description",
        ]

Creating View

Create view refers to the creation of a new instance in a table. We can understand it as similar to receiving data from a user and inserting it into the table.

In ninja/views.py

from django.shortcuts import render

# relative import of forms
from .models import NinjaModel
from .forms import NinjaForm


def create_view(request):
    # dictionary for initial data with
    # field names as keys
    context ={}

    # add the dictionary during initialization
    form = NinjaForm(request.POST or None)
    if form.is_valid():
        form.save()
      
    context['form']= form
    return render(request, "create_view.html", context)

 

Now create a template in templates/create_view.html

<form method="POST" enctype="multipart/form-data">
 
    <!-- Security token -->
    {% csrf_token %}
 
    <!-- Using the formset -->
    {{ form.as_p }}
    
    <input type="submit" value="Submit">
</form>

Retrieve View

Retrieve view is divided into two types of views, ListView and Detail View.

First, we will learn about List View.

List View

It is basically listing all particular instances of a table from the database. It is used to display many types of data in the form of a list.

In ninja/views.py

from django.shortcuts import render
 
# relative import of forms
from .models import NinjaModel
 
 
def list_view(request):
    # dictionary for initial data with
    # field names as keys
    context ={}
 
    # add the dictionary during initialization
    context["dataset"] = NinjaModel.objects.all()
        
    return render(request, "list_view.html", context)

 Now create a template in templates/liist_view.html

<div class="main">
 
    {% for data in dataset %}.
 
    {{ data.title }}<br/>
    {{ data.description }}<br/>
    <hr/>
 
    {% endfor %}
 
</div>

Detail View

It is basically displaying all particular instances of a table from the database with necessary details. It is used to display many types of data in a single sheet.

In ninja/views.py,

from django.urls import path
 
# importing views from views..py
from .views import detail_view
 
urlpatterns = [
    path('<id>', detail_view ),
]

Now creating Templates and views for the same. In ninja/views.py

from django.urls import path
 
# importing views from views..py
from .views import detail_view
 
urlpatterns = [
    path('<id>', detail_view ),
]

from django.shortcuts import render

# relative import of forms
from .models import NinjaModel

# pass id attribute from urls
def detail_view(request, id):
   # dictionary for initial data with
    # field names as keys
    context ={}

    # add the dictionary during initialization
    context["data"] = NinjaModel.objects.get(id = id)
      
    return render(request, "detail_view.html", context)

 

 

Now create a template.

<div class="main">
    
   <!-- Specify fields to be displayed -->
    {{ data.title }}<br/>
    {{ data.description }}<br/>
 
</div>

 

Let’s move on to perform operations.

Update View

As the name suggests, it means updating the instance of entries in the table from the database with some other details. It takes the changes made by the user and edit it accordingly in the database

Now making changes in ninja/views.py

from django.shortcuts import (get_object_or_404,
                            render,
                            HttpResponseRedirect)

# relative import of forms
from .models import NinjaModel
from .forms import NinjaForm

# after updating it will redirect to detail_View
def detail_view(request, id):
    # dictionary for initial data with
        # add the dictionary during initialization
    # field names as keys
    context ={}

context["data"] = NinjaModel.objects.get(id = id)
      
    return render(request, "detail_view.html", context)

# update view for details
def update_view(request, id):
    # dictionary for initial data with
    # field names as keys
    context ={}

    # fetch the object related to passed id
    obj = get_object_or_404(NinjaModel, id = id)

    # pass the object as instance in form
    form = NinjaForm(request.POST or None, instance = obj)

   # save the data from the form and
    # redirect to detail_view
    if form.is_valid():
        form.save()
        return HttpResponseRedirect("/"+id)

    # add form dictionary to context
    context["form"] = form

    return render(request, "update_view.html"context)


 

 

Now creating Template in Template folder

<div class="main">
    <!-- Create a Form -->
    <form method="POST">
        <!-- Security token by Django -->
        {% csrf_token %}

        <!-- form as paragraph -->
        {{ form.as_p }}

        <input type="submit" value="Update">
    </form>

</div>

 

 

In ninja/template/detail_view.html

<div class="main">
    <!-- Display attributes of instance -->
    {{ data.title }} <br/>
    {{ data.description }}
</div>

 

Delete View

Delete view refers to the logic of deleting a particular instance from the table of the database. According to the need of the user, the delete operations remove the instance of that entry.

In ninja/ views.py

from django.shortcuts import get_object_or_404, render
from.models import NinjaModel


# delete view for details
def delete_view(request, id):
    # dictionary for initial data with
    # field names as keys
    context ={}

    # fetch the object related to passed id
    obj = get_object_or_404(NinjaModel, id = id)


    if request.method =="POST":
       # delete object
        obj.delete()
        # after deleting redirect to
        # home page
        return HttpResponseRedirect("/")

    return render(request, "delete_view.html", context)

                      HttpResponseRedirect)

 

Now we are mapping the URL

In ninja/urls.py

from django.urls import path

# importing views from views..py
from .views import delete_view
urlpatterns = [
    path('<id>/delete', delete_view ),
]

 

 

Now creating a template

<div class="main">
    <!-- Create a Form -->
    <form method="POST">
       <!-- Security token by Django -->
        {% csrf_token %}
        Are you want to delete this item ?
        <input type="submit" value="Yes" />
        <a href="/">Cancel </a>
    </form>
</div>

 

This was all about CRUD Operations in Django.

Frequently Ask Questions

  1. What do you mean by CRUD?
    CRUD is a set of create, retrieve, utilize, delete operations.
     
  2. How many types of retrieve operations are there?
    There are two types i.e., list view and detail view.
     
  3. Where do CRUD operations work?
    They work in the tables of the database.
     
  4. Can we delete something from the database?
    Yes, we can do this by using the delete operation.

Key Takeaways

In this blog, we have learned about Django and CRUD operations, how to use them, their meaning, and much more. 

There is much more to learn in Django. As it is a widely used framework nowadays, So if you

want to learn more about Django that which among Django and flask is better to click to here

Live masterclass