Django最后一页分页重定向 [英] Django last page pagination redirect

查看:169
本文介绍了Django最后一页分页重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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.

推荐答案

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

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)

这篇关于Django最后一页分页重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆