如何在django中使用分页时返回最后一页?

时间:2015-09-15 06:19:29

标签: django django-pagination

在一个简单的论坛中,我使用原生django Pagination我希望用户在发布后可以定向到帖子中的最后一页。

这是视图

@login_required
def topic_reply(request, topic_id):
    tform = PostForm()
    topic = Topic.objects.get(pk=topic_id)
    args = {}
    posts = Post.objects.filter(topic= topic)
    posts =  Paginator(posts,10)


    if request.method == 'POST':
        post = PostForm(request.POST)


        if post.is_valid():
            p = post.save(commit = False)
            p.topic = topic
            p.title = post.cleaned_data['title']
            p.body = post.cleaned_data['body']
            p.creator = request.user

            p.save()

            return HttpResponseRedirect('/forum/topic/%s/?page=%s'  % (topic.slug, posts.page_range[-1]))

    else:
        args.update(csrf(request))
        args['form'] = tform
        args['topic'] = topic
        return render_to_response('myforum/reply.html', args, 
                                  context_instance=RequestContext(request)) 

哪个收益率:

'Page' object has no attribute 'page_range'

我尝试了其他技巧:

posts = list(Post.objects.filter(topic= topic))

但没有效果。所以留下了无知,并欣赏你的提示。

1 个答案:

答案 0 :(得分:4)

尝试使用num_pages。最后一页的编号应该等于页数。

return HttpResponseRedirect('/forum/topic/%s/?page=%s'  % (topic.slug, posts.num_pages))