Transforming Function Based View To Class Based View
I think it should be simpler but here's my function based view with filter def withSub(request): post = Post.objects.filter(with_or_without_sub='WS') paginator = Paginator(
Solution 1:
It could be something like the follows. You might need to test and debug. The request.GET
is used, so it's get.
from django.views.generic.listimport ListView
classPostListView(ListView):
model = Post
template_name = 'community/home.html'# <app>/<model>_<viewtype>.htmldefget(self, request, *args, **kwargs):
post = Post.objects.filter(with_or_without_sub='WS')
paginator = Paginator(post, 2)
page = request.GET.get('page')
post = paginator.get_page(page)
content_dict = {
'posts':post,
'paginator':paginator
}
context = self.get_context_data()
context.update(content_dict)
return self.render_to_response(context)
Solution 2:
If you want to customise the queryset, use the queryset
attribute:
classPostListView(ListView):
queryset = Post.objects.filter(with_or_without_sub='WS')
template_name = 'community/home.html'
Solution 3:
You get either set a specific queryset, like this:
queryset = Post.objects.filter(with_or_without_sub='WS')
or if there's more complex logic eventually involved, you can override the get_queryset()
method of the view, like this:
from django.views.generic.listimport ListView
classPostListView(ListView):
model = Post
template_name = 'community/home.html'defget_queryset(self):
return Post.objects.filter(with_or_without_sub='WS', ...)
Post a Comment for "Transforming Function Based View To Class Based View"