0
0
Djangoframework~30 mins

DeleteView for removal in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
DeleteView for removal
📖 Scenario: You are building a simple Django app to manage a list of books. You want to allow users to delete a book from the list using Django's built-in DeleteView.
🎯 Goal: Create a Django DeleteView to remove a book from the database. The view should use the correct model, template, and redirect URL after deletion.
📋 What You'll Learn
Create a Django model called Book with fields title and author.
Create a DeleteView class called BookDeleteView that deletes a Book instance.
Set the model attribute of BookDeleteView to Book.
Set the template_name attribute of BookDeleteView to book_confirm_delete.html.
Set the success_url attribute of BookDeleteView to reverse_lazy('book-list').
💡 Why This Matters
🌍 Real World
Deleting records is a common feature in web apps, such as removing posts, products, or user data.
💼 Career
Understanding Django's class-based views like DeleteView is essential for building maintainable and efficient web applications.
Progress0 / 4 steps
1
Create the Book model
Create a Django model called Book with two fields: title as a CharField with max length 100, and author as a CharField with max length 100.
Django
Need a hint?

Use models.CharField(max_length=100) for both fields inside the Book class.

2
Import DeleteView and reverse_lazy
Import DeleteView from django.views.generic and reverse_lazy from django.urls.
Django
Need a hint?

Use from django.views.generic import DeleteView and from django.urls import reverse_lazy.

3
Create the BookDeleteView class
Create a class called BookDeleteView that inherits from DeleteView. Set its model attribute to Book, template_name to 'book_confirm_delete.html', and success_url to reverse_lazy('book-list').
Django
Need a hint?

Define BookDeleteView as a subclass of DeleteView and set the three attributes exactly as specified.

4
Add URL pattern for BookDeleteView
Add a URL pattern to urls.py that maps the path 'book/delete/<int:pk>/' to BookDeleteView.as_view() with the name 'book-delete'.
Django
Need a hint?

Use path('book/delete//', BookDeleteView.as_view(), name='book-delete') inside urlpatterns.