In most cases, we write view functions in views.py. However, we may write many duplicate codes such as post_list = Post.objects.all() and post = get_object_or_404(Post, pk = pk). In order to solve this problem, Django provides us generic view class. There are two common class we can inherite. One is ListView, the other is DetailView.

Class based view

1
2
3
4
5
6
7
8
class PostView(ListView):
model = Post
template_name = 'blog/index.html'
context_object_name = 'post_list'

def get_queryset(self):
cate = get_object_or_404(Category, pk=self.kwargs.get('pk'))
return super(CategoryView, self).get_queryset().filter(category=cate)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class PostDetailView(DetailView):
model = Post
template_name = 'blog/detail.html'
context_object_name = 'post'

def get(self, request, *args, **kwargs):
# rewrite get method to implemente extra functions
response = super(PostDetailView, self).get(request, *args, **kwargs)
self.object.increase_views()
# return HttpResponse object
return response
def get_context_data(self, **kwargs):
# rewrite get_context_data method to return extra context data
context = super(PostDetailView, self).get_context_data(**kwargs)
form = CommentForm()
comment_list = self.object.comment_set.all()
context.update({
'form': form,
'comment_list': comment_list
})
return context

Mixin