Do you think IIT Guwahati certified course can help you in your career?
No
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" classNinjaModel(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.
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 classNinjaForm(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
defcreate_view(request): # dictionary for initial data with # field names as keys context ={}
# add the dictionary during initialization form = NinjaForm(request.POST orNone) 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
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 deflist_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 ={}
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 defdelete_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("/")
# 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
What do you mean by CRUD? CRUD is a set of create, retrieve, utilize, delete operations.
How many types of retrieve operations are there? There are two types i.e., list view and detail view.
Where do CRUD operations work? They work in the tables of the database.
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