</>
Skip to content
Django lessons (34/43)

Django — Generic Views

ListView

from django.views.generic import ListView
from .models import Post

class PostListView(ListView):
    model = Post
    template_name = 'blog/list.html'
    context_object_name = 'posts'
    paginate_by = 10
    
    def get_queryset(self):
        return Post.objects.filter(published=True)

DetailView

class PostDetailView(DetailView):
    model = Post
    template_name = 'blog/detail.html'
    context_object_name = 'post'
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['comments'] = self.object.comments.all()
        return context

CreateView

from django.contrib.auth.mixins import LoginRequiredMixin

class PostCreateView(LoginRequiredMixin, CreateView):
    model = Post
    template_name = 'blog/form.html'
    fields = ['title', 'content']
    
    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

UpdateView

class PostUpdateView(UpdateView):
    model = Post
    template_name = 'blog/form.html'
    fields = ['title', 'content']

DeleteView

class PostDeleteView(DeleteView):
    model = Post
    template_name = 'blog/confirm_delete.html'
    success_url = reverse_lazy('post-list')

Mini Practice

  1. Create a ListView with filtering
  2. Add context data to DetailView
  3. Use CreateView with authentication
  4. Implement UpdateView and DeleteView

Up Next

Continue with Signals — Django signals and events.

Related Topics

Frequently Asked Questions about Generic Views

What is Generic Views in Django?

Generic Views is a fundamental concept in Django. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Generic Views?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Generic Views.

Why is Generic Views important in Django?

Generic Views is essential for Django development. Understanding this concept will help you write better code and solve real-world problems more effectively.