Django 最后一页分页重定向

Django last page pagination redirect

我的问题类似于问题。唯一的区别是我使用 GCBV 进行分页。我的查看文件如下:

class ChatListView(ListView):
    model = Chat
    form_class = NewMessageForm
    template_name = 'chat.html'
    paginate_by = 5
    queryset = model.objects.all() ###not needed


    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST)        
        if form.is_valid():
            form.save()
            return redirect('chat') <--- here
        return render(request, self.template_name, {'form': form})

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)  
        context['form'] = NewMessageForm() # edited: self.form_class
        return context

我想要post方法重定向到分页的最后一页。在link中,由return HttpResponseRedirect('/forum/topic/%s/?page=%s' % (topic.slug, posts.num_pages))实现。但是对于我的 GCBV,我不知道如何通过对象获取 .num_pages。请提供一点帮助。

您可以调用 get_context_data,这将对查询集进行分页并在上下文中包含 paginator。然后,您可以使用 paginator.num_pages.

访问页数
from django.urls import reverse

class ChatListView(ListView):
    ...

    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST)        
        if form.is_valid():
            form.save()
            self.object_list = self.get_queryset()  # get_context_data expects self.object_list to be set
            context = self.get_context_data()
            paginator = context['paginator']
            num_pages = paginator.num_pages
            return redirect(reverse('chat') + '?page=%s' % paginator.num_pages)