A DeleteView is a built-in class-based view used to remove a record from the database. It automatically fetches the record, shows a confirmation page, deletes the record, and redirects.
- Specify the model that contains the record to be deleted.
- Provide a template to show the delete confirmation page.
- Set a success URL to redirect after the record is deleted.
Example: Consider a project named 'geeksforgeeks' having an app named 'geeks'. 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:
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
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
Let's create some instances of this model using shell, enter the following command to launch Python shell:
Python manage.py shell
Enter following commands to create entries in database:
>>> from geeks.models import GeeksModel
>>> GeeksModel.objects.create( title="title1", description="description1")
>>> GeeksModel.objects.create(title="title2", description="description2")
>>> GeeksModel.objects.create(title="title3", description="description3")
Now we have everything ready for back end. Verify that instances have been created from http://localhost:8000/admin/geeks/geeksmodel/
Class Based Views automatically setup everything. One just needs to specify which model to create DeleteView for, then Class based DeleteView will automatically try to find a template in app_name/modelname_confirm_delete.html. In our case it is geeks/templates/geeks/geeksmodel_confirm_delete.html.
Create class based view in geeks/views.py:
from django.views.generic.edit import DeleteView
# Relative import of GeeksModel
from .models import GeeksModel
class GeeksDeleteView(DeleteView):
# specify the model you want to use
model = GeeksModel
# can specify success url
# url to redirect after successfully
# deleting object
success_url ="/"
template_name = "geeks/geeksmodel_confirm_delete.html"
Now create a url path to map the view. In geeks/urls.py:
from django.urls import path
# importing views from views..py
from .views import GeeksDeleteView
urlpatterns = [
# <pk> is identification for id field,
# slug can also be used
path('<pk>/delete/', GeeksDeleteView.as_view()),
]
Create a template in templates/geeks/geeksmodel_confirm_delete.html:
<form method="post">{% csrf_token %}
<p>Are you sure you want to delete "{{ object }}"?</p>
<input type="submit" value="Confirm">
</form>
Check what is there on: http://localhost:8000/1/delete

Tap confirm and object will redirect to "success_url" defined in the view. Let's check if title1 is deleted from database.
