I am trying to convert this function-based view to a class-based view for the purpose of pagination.
def tag(request, tag):
posts = Post.objects.filter(approved=True, tags__name__in=[tag]).order_by('-date_posted')
return render(request, 'blog/tag.html', {'tag': tag, 'posts': posts})
I wrote it like this:
class TagView(ListView):
model = Post
template_name = 'blog/tag.html'
context_object_name = 'posts'
ordering = ['-date_posted']
paginate_by = 3
def get_queryset(self):
return Post.objects.filter(approved=True, tags__name__in=[tag]).order_by('-date_posted')
But this does not display any posts when I load the page. Can anyone tell me why this is? Or if you know another way of paginating this view without converting it to a class-based view that would also be appreciated. Thank you in advance.
CodePudding user response:
In your ListView you are not passing any data into the [tag] variable, so your queryset is returning empty. Depending on what you're passing to it, you may or may not need the [] square brackets around it in the query.
If you are using a single string tag, eg, via the URL /tag/myTag then to pass data from the URL into a listview you can update your get_queryset method:
def get_queryset(self):
return Post.objects.filter(approved=True, tags__name__in=[self.kwargs['tag']]).order_by('-date_posted')
If you are passing an actual a list of tags, you may need to set it in a session variable in the previous view and recall it here
In the previous view
request.session['tags'] = list_of_tags
And in this view
tags = request.session['tags']
return Post.objects.filter(approved=True, tags__name__in=tags).order_by('-date_posted')