Class-Based Views (CBV) & Generic Views

🐍 DjangoLesson 10Intermediate

Class-Based Views (CBVs) provide an alternative way to implement views as Python objects instead of functions, promoting reusability and organization using inheritance.

1 Generic Views Examples
Python — views.py
from django.views.generic import ListView, DetailView, CreateView
from django.urls import reverse_lazy
from .models import Post

class PostListView(ListView):
    model = Post
    template_name = "posts/list.html"
    context_object_name = "posts"
    paginate_by = 10

    def get_queryset(self):
        return Post.objects.filter(is_published=True).order_by("-created_at")

class PostCreateView(CreateView):
    model = Post
    fields = ["title", "content", "category"]
    success_url = reverse_lazy("post-list")

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)
2 Code Challenge
Challenge: Rewrite your basic UpdateView to edit dynamic posts, ensuring that users can only update posts which they authored.