Search code examples
djangodjango-viewsdjango-pagination

Django last page pagination redirect


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.


Solution

  • 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)