Django provides built-in generic class-based views to handle common CRUD operations efficiently, reducing boilerplate code and improving maintainability.
Generic views are pre-built Django views designed to handle common patterns such as listing objects, viewing details, creating, updating, and deleting records.
Displays a list of objects from a model.
# Displays a list of Book objects
from django.views.generic import ListView
from .models import Book
class BookListView(ListView):
model = Book
template_name = 'book_list.html'
context_object_name = 'books'
Shows detailed information for a single object.
# Shows details of a single Book
from django.views.generic import DetailView
from .models import Book
class BookDetailView(DetailView):
model = Book
template_name = 'book_detail.html'
context_object_name = 'book'
Handles object creation with a form.
# Creates a new Book entry
from django.views.generic import CreateView
from django.urls import reverse_lazy
from .models import Book
class BookCreateView(CreateView):
model = Book
fields = ['title','author','price']
template_name = 'book_form.html'
success_url = reverse_lazy('book_list')
Updates an existing object.
# Updates an existing Book
from django.views.generic import UpdateView
from django.urls import reverse_lazy
from .models import Book
class BookUpdateView(UpdateView):
model = Book
fields = ['title','author','price']
template_name = 'book_form.html'
success_url = reverse_lazy('book_list')
Deletes an object after confirmation.
# Deletes a Book object
from django.views.generic import DeleteView
from django.urls import reverse_lazy
from .models import Book
class BookDeleteView(DeleteView):
model = Book
template_name = 'book_confirm_delete.html'
success_url = reverse_lazy('book_list')
Click the buttons below to interact with a JavaScript simulation of how these Django views behave in a real browser.
*Note: This is a frontend simulation. In Django, these operations happen on the server.
reverse_lazy in class-based viewscontext_object_name for clarity