我有一个搜索按钮,允许用户在我的博客应用程序中搜索字符串。我使用ListView。问题是paginate_by不起作用。从代码中可以看出,还有两个具有相同模板的listview。在这些情况下,paginate_by确实可以正常工作。请参见下面的代码。 paginate_by对于BlogListView和BlogAuthorListView正常工作,但对于BlogSearchView无效。否则BlogSearchView可以正常运行。
我尝试在类派生中包括MultipleObjectMixin。但这与ListView不兼容
class BlogListView(LoginRequiredMixin, ListView):
model = Post
fields = '__all__'
template_name = 'blog/home.html'
context_object_name = 'posts'
ordering = '-date_posted'
paginate_by = 3
class BlogAuthorListView(ListView):
model = Post
fields = '__all__'
template_name = 'blog/home.html'
context_object_name = 'posts'
ordering = '-date_posted'
paginate_by = 3
def get_queryset(self):
user = get_object_or_404(User, username=self.kwargs.get('username'))
return Post.objects.filter(author=user).order_by('-date_posted')
class BlogSearchView( ListView):
model = Post
fields = '__all__'
template_name = 'blog/home.html'
context_object_name = 'posts'
ordering = '-date_posted'
paginate_by = 3
def post(self, request, *args, **kwargs):
search_text = request.POST.get('search_text')
posts = Post.objects.filter(Q(content__contains=search_text) | Q(title__contains=search_text))
return render(request, self.template_name, {'posts': posts, 'search_text': search_text })