0
0
Djangoframework~5 mins

DeleteView for removal in Django

Choose your learning style9 modes available
Introduction

DeleteView helps you easily remove an item from your database with a simple web page. It handles showing a confirmation and deleting the item for you.

When you want users to delete a blog post from your website.
When you need to remove a product from an online store catalog.
When an admin wants to delete a user account safely.
When you want to confirm before deleting important data.
When you want to redirect users after deleting an item.
Syntax
Django
from django.views.generic.edit import DeleteView
from django.urls import reverse_lazy

class YourModelDeleteView(DeleteView):
    model = YourModel
    template_name = 'yourmodel_confirm_delete.html'
    success_url = reverse_lazy('yourmodel-list')

model tells which data to delete.

template_name is the page shown to confirm deletion.

success_url is where to go after deletion.

Examples
This deletes a Book object and redirects to the book list page after confirmation.
Django
from django.views.generic.edit import DeleteView
from django.urls import reverse_lazy

class BookDeleteView(DeleteView):
    model = Book
    template_name = 'book_confirm_delete.html'
    success_url = reverse_lazy('book-list')
If you don't specify template_name, Django uses a default confirmation page.
Django
from django.views.generic.edit import DeleteView
from django.urls import reverse_lazy

class ArticleDeleteView(DeleteView):
    model = Article
    success_url = reverse_lazy('home')
Sample Program

This example shows a Django model Item and a DeleteView to remove an item. The confirmation page asks the user if they want to delete the item by name. After deletion, it redirects to the item list page.

Django
from django.urls import path, reverse_lazy
from django.views.generic.edit import DeleteView
from django.db import models

# Simple model
class Item(models.Model):
    name = models.CharField(max_length=100)

# DeleteView for Item
class ItemDeleteView(DeleteView):
    model = Item
    template_name = 'item_confirm_delete.html'
    success_url = reverse_lazy('item-list')

# URL patterns
urlpatterns = [
    path('item/<int:pk>/delete/', ItemDeleteView.as_view(), name='item-delete'),
]

# Template: item_confirm_delete.html
# <h1>Are you sure you want to delete {{ object.name }}?</h1>
# <form method="post">{% csrf_token %}<button type="submit">Yes, delete</button></form>
OutputSuccess
Important Notes

Always use reverse_lazy for success_url to avoid errors during import time.

The confirmation template receives the object as object to show details.

Make sure to protect delete views with permissions to avoid unwanted deletions.

Summary

DeleteView makes deleting database items easy with confirmation pages.

Set model, template_name, and success_url to use it.

It handles showing the confirmation and deleting the item automatically.