Django last page pagination redirect

假如想象 提交于 2020-01-06 03:57:06

问题


My problem is similar to this problem. The only difference is I use GCBV for my pagination. My view file is as follows:

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

What I want the post method to redirect to the last page of the pagination. In the link, it was achieved by return HttpResponseRedirect('/forum/topic/%s/?page=%s' % (topic.slug, posts.num_pages)). But for my GCBV, I don't know how to get the .num_pages via an object. A little help please.


回答1:


You could call get_context_data, which will paginate the queryset and include paginator in the context. You can then access the number of pages with 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)


来源:https://stackoverflow.com/questions/48094350/django-last-page-pagination-redirect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!