Building CRUD (Create, Read, Update, Delete) operations is the core requirement of database-backed web development. Django provides three specialized generic editing views that handle form rendering, validation cycles, database persistence, and redirection: CreateView, UpdateView, and DeleteView.
# blog/views.py
from django.views.generic.edit import CreateView
from django.urls import reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin
from .models import BlogPost
class BlogPostCreateView(LoginRequiredMixin, CreateView):
model = BlogPost
fields = ['title', 'summary', 'content', 'category', 'is_published']
template_name = 'blog/post_form.html'
success_url = reverse_lazy('blog:post_list')
def form_valid(self, form):
"""Automatically bind logged-in author before saving record."""
form.instance.author = self.request.user.profile
return super().form_valid(form)
from django.views.generic.edit import UpdateView
from django.core.exceptions import PermissionDenied
class BlogPostUpdateView(LoginRequiredMixin, UpdateView):
model = BlogPost
fields = ['title', 'summary', 'content', 'category', 'is_published']
template_name = 'blog/post_form.html'
slug_field = 'slug'
def get_object(self, queryset=None):
"""Ensure users can only edit their own authored articles."""
obj = super().get_object(queryset)
if obj.author.user != self.request.user:
raise PermissionDenied("You do not have permission to edit this post.")
return obj
from django.views.generic.edit import DeleteView
class BlogPostDeleteView(LoginRequiredMixin, DeleteView):
model = BlogPost
template_name = 'blog/post_confirm_delete.html'
success_url = reverse_lazy('blog:post_list')
slug_field = 'slug'
When setting success_url on a class level in CBVs, always use reverse_lazy() instead of reverse()! Because Python evaluates class attributes when the module is imported — before URLconf has finished loading — standard reverse() will raise a NoReverseMatch error.
Broaden your backend architecture, REST API design, and production engineering expertise:
Core inheritance hierarchy underpinning all editing views.
Customize the form_class used by CreateView and UpdateView.
Configure success_url or get_absolute_url() after form submissions.
Build an interactive CRUD application using editing class-based views.