Delete View – Function based Views Django

Delete View refers to a view (logic) to delete a particular instance of a table from the database. It is used to delete enteries in the database for example, deleting an article at geeksforgeeks. So Delete view must show a confirmation message to the user and should delete the instance automatically. Django provides extra-ordinary support for Delete Views but let’s check how it is done manually through a function-based view. This article revolves around Delete View which involves concepts such as Django Forms, Django Models.
For Delete View, we need a project with some models and multiple instances that we can use for deleting.

Django Delete View – Function Based Views

Illustration of How to create and use Delete view using an Example. Consider a project named geeksforgeeks having an app named geeks.

Refer to the following articles to check how to create a project and an app in Django.

After you have a project and an app, let’s create a model of which we will be creating instances through our view. In geeks/models.py,

filter_none

edit
close

play_arrow

link
brightness_4
code

# import the standard Django Model
# from built-in library
from django.db import models
   
# declare a new model with a name "GeeksModel"
class GeeksModel(models.Model):
  
    # fields of the model
    title = models.CharField(max_length = 200)
    description = models.TextField()
  
    # renames the instances of the model
    # with their title name
    def __str__(self):
        return self.title

chevron_right


After creating this model, we need to run two commands in order to create Database for the same.



Python manage.py makemigrations
Python manage.py migrate

Now let’s create some instances of this model using shell, run form bash,

Python manage.py shell

Enter following commands

>>> from geeks.models import GeeksModel
>>> GeeksModel.objects.create(
                       title="title1",
                       description="description1").save()
>>> GeeksModel.objects.create(
                       title="title2",
                       description="description2").save()
>>> GeeksModel.objects.create(
                       title="title2",
                       description="description2").save()

Now we have everything ready for back end. Verify that instances have been created from http://localhost:8000/admin/geeks/geeksmodel/

django-Updateview-check-models-instances

Now let’s create our delete view first, In geeks/views.py

filter_none

edit
close

play_arrow

link
brightness_4
code

from django.shortcuts import (get_object_or_404,
                              render, 
                              HttpResponseRedirect)
  
from .models import GeeksModel
  
  
# 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(GeeksModel, 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)

chevron_right


Now a url mapping to this view with a regular expression of id,
In geeks/urls.py

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Template for delete view includes a simple form confirming whether user wants to delete the instance or not. In geeks/templates/delete_view.html,

filter_none

edit
close

play_arrow

link
brightness_4
code

<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>

chevron_right


Everything ready, now let’s check if it is working or not, visit http://localhost:8000/2/delete
django-delete-view
Let’s check if instance has been deleted or not,
django-deleteview-
One can implement this view in any manner as per requirement using obj.delete() function.

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

Software Developer at GeeksForGeeks

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.