Django DeleteView¶
Why Django DeleteView?¶
- It's required to implement the delete a given resource from the database.
- Django generic
DeleteView
provides the functionality to display a confirmation page and deletes the object - On
GET
request it displays the confirmation page - On
POST
request it deletes the request resource. - After deleting the resource it redirects the page to the
success_url
quick use of Django DeleteView¶
usecase: Delete a product from the product table.
myapp/models.py
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
class Meta:
db_table = 'product'
def __str__(self):
return f'{self.name}'
Create object and get the id¶
Let's open the django shell with command python manage.py shell
execute below code to create product instance and get the id.
from app.models import Product
obj = Product.objects.create(name='Quick python', description='a python book')
print(obj.id)
# 1
myapp/views.py
from django.urls import reverse_lazy
from django.views.generic.edit import DeleteView
from myapp.models import Product
class ProductDeleteView(DeleteView):
model = Product
success_url = reverse_lazy('product-list')
templates/product_delete.html
<form method="post">{% csrf_token %}
<p>Are you sure you want to delete "{{ object }}"?</p>
{{ form }}
<input type="submit" value="Confirm">
</form>
myapp/urls.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('products/', views.ProductListView.as_view(), name='product-list'),
path('products/<pk>', views.ProductDeleteView.as_view(), name='product-delete')
]
Now, we are ready to test the generic DeleteView. Let's use the product id and delete it. To do that let's access the url http://localhost:8000/products/1
Note: replace
1
with actual id.
Now, it will ask us to confirm the deletion. Once you click on the confirm, it will delete the object. Let's confirm that whether the object get deleted or not with below query.
from myapp.models import Product
obj = Product.objects.get(id=1)
# DoesNotExist error
The above query will throw an DoesNotExist
error as it was deleted. You can find the sample project in github
Reference: