Search code examples
djangodjango-pagination

How to return the last page when using pagination in django?


In a simple forum, I'm using native django Pagination I'd like users to be directed to the last page in a thread after they posted there.

Here is the view

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

Which yields:

'Page' object has no attribute 'page_range'

I tried other tricks like:

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

but none worked. So left clueless and appreciate your hints.


Solution

  • Try using num_pages. The last page number should be equal to the number of pages.

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