Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages
wb_sunny

Django CRUD Application

Django CRUD Application (2)

In this article, we will know what Django CRUD application consists of and then later create our very own CRUD application.

What is a Django CRUD application?

A CRUD application is a website that deals with the CRUD-Create, Retrieve, Update, and Delete operations.  A typical example of a CRUD application is a Student data application. In such applications, you can:

  • Add/Create new Student data
  • Retrieve the present student’s data
  • Update/Edit an already student’s data
  • Delete a student data

We will now learn about each of these operations 

CRUD
CRUD
  • Create: Create or add new entries into the database
  • Retrieve: Get the entries/entry from the Database
  • Update: Update a particular entry in the database
  • Delete: Delete a particular entry from the database

Creating our own CRUD application in Django

Let us now create a simple Student Data CRUD application.

1. Creating a Model Table

To store the data, we need to create a Django model. Hence add the following model into your file.

class StudentModel(models.Model):
    id = models.IntegerField(primary_key = True)
    student_name = models.CharField(max_length=80)
    rollnumber = models.CharField(max_length=10)
    student_class = models.IntegerField()
    student_age = models.IntegerField()

    def __str__(self):
        return f"{self.student_name} : {self.rollnumber}"

2. Creating a Model Form

Also we will require a Model Form to display the model fields to the users.

class StudentForm(forms.ModelForm):
    class Meta:
        model = StudentModel
        fields = ('id','student_name','rollnumber','student_class','student_age')

3. Coding the Create View

In Views.py create the View “CreateView” and add the following code:

from .models import StudentModel
from .forms import StudentForm
from django.shortcuts import render,redirect

def CreateView(request):
    if request.method == 'POST':
        form = StudentForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('/data')
    else:
        form =StudentForm()
        context = {
            'form':form
        }
        return render(request,'create.html',context)

The template “create.html” will look like:

<form method = "post">
    {% csrf_token %}
    {{form.as_p}}
    <input type = "submit" value = "submit">
</form>

The URL path for the View will be:

path('data/create', CreateView),

4. Coding the Retrieve View

Now in the retrieve operation, there are two ways possible

Therefore, add both the following Views into your views.py file

from django.shortcuts import render,redirect
from .models import StudentModel
from .forms import StudentForm

def Retrieve_ListView(request):
    dataset = StudentModel.objects.all()
    return render(request,'listview.html',{'dataset':dataset})

def Retrieve_DetailView(request,_id):
    try:
        data =StudentModel.objects.get(id =_id)
    except StudentModel.DoesNotExist:
        raise Http404('Data does not exist')

    return render(request,'detailview.html',{'data':data})

The Corresponding ListView template will be:

{% for data in dataset %}
{{data}}
<hr>
{% endfor %}

The Corresponding DetailView template will be:

<h3>Name:{{data.student_name}}</h3><br>
<h3>Roll Number:{{data.rollnumber}}</h3><br>
<h3>Class:{{data.student_class}}</h3><br>
<h3>Age:{{data.student_age}}</h3><br>
<hr/>

The URL paths for the Views will be:

    path('data/', Retrieve_ListView),
    path('data/<int:_id>',Retrieve_DetailView),

5. Coding the Update View

Now add the following Update View into the views.py file

from django.shortcuts import render,redirect,get_object_or_404
from .models import StudentModel
from .forms import StudentForm

def UpdateView(request,_id):
    try:
        old_data = get_object_or_404(StudentModel,id =_id)
    except Exception:
        raise Http404('Does Not Exist')

    if request.method =='POST':
        form =StudentForm(request.POST, instance =old_data)

        if form.is_valid():
            form.save()
            return redirect(f'/data/{_id}')
    
    else:

        form = StudentForm(instance = old_data)
        context ={
            'form':form
        }
        return render(request,'update.html',context)

The corresponding update.html template will look like:

<form method="post">
    {% csrf_token %}
    {{form.as_p}}
    <input type="submit" value = "Update">
</form>

The URL path for the View will be:

path('data/<int:_id>/update', UpdateView),

6. Coding the Delete View

Now add the Delete View into your views.py file

def DeleteView(request,_id):
    try:
        data = get_object_or_404(StudentModel,id =_id)
    except Exception:
        raise Http404('Does Not Exist')

    if request.method == 'POST':
        data.delete()
        return redirect('/data')
    else:
        return render(request, 'delete.html')

The corresponding delete.html will look like:

<form method="post">
    {% csrf_token %}
    Click YES to confirm
    <input type = "submit" value="YES">
    <a href='/data'>Cancel</a>
</form>

The URL path for the View will be:

path('data/<int:_id>/delete', DeleteView),

Implementing the Student’s App

That’s it with the coding part !! Now fire up the server and let’s go to “/data/create” endpoint 

Create
Create

Hit submit and you will reach the “/data” page where the list of students is displayed.

Retrieve List View
Retrieve List View

Now try the “/data/1” endpoint

Retrieve Detail View
Retrieve Detail View

Okay guys !! lets us update the first entry. Go to “/data/1/update

Update
Update

Make some changes and hit Update, you will be redirected to the Detail View Page of the particular student.

And lastly let’s try to delete the first student. Go to “/data/1/delete

Delete
Delete

Hit YES and check, the particular student data will be removed from the DB.

Conclusion

That’s it, Coders!! This was all about CRUD applications. Do check out the Django REST API tutorial, which is the REST API version of a CRUD application. 

See you in the next article!! Till then keep coding !!