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.
DeleteView for removal in 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.
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')
template_name, Django uses a default confirmation page.from django.views.generic.edit import DeleteView from django.urls import reverse_lazy class ArticleDeleteView(DeleteView): model = Article success_url = reverse_lazy('home')
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.
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>
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.
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.