Charles Smith
Charles Smith

Reputation: 3289

Django Paginator Limiting Iteration of all Objects

I have a standard blog on my site that I added pagination to with Django Paginator. I also have a sidebar that iterates over all Posts and displays title and link. Everything seems to work for the most part except in list_view the sidebar only displays the titles and links to posts visible on the current page, but in detail_view all titles and links are available. I know why its doing it, I just don't understand how to fix it.

Below is a copy of my list_view and a couple screenshots for easier reference. Thank you.

post_list

def post_list(request, tag_slug=None):
    posts = Post.published.all()
    tag = None

    if tag_slug:
        tag = get_object_or_404(Tag, slug=tag_slug)
        posts = posts.filter(tags__in=[tag])

    paginator = Paginator(posts, 3)  # 3 posts in each page
    page = request.GET.get('page')
    try:
        posts = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer deliver the first page
        posts = paginator.page(1)
    except EmptyPage:
        # If page is out of range deliver last page of results
        posts = paginator.page(paginator.num_pages)
    return render(request, 'press/post_list.html', {'page': page, 'posts': posts, 'tag': tag})

List View

Detail View

Upvotes: 0

Views: 1162

Answers (1)

Bobby Chowdhury
Bobby Chowdhury

Reputation: 334

send the "posts" list separately for all posts without applying paginator. Send the paginated ones in a separate list variable such as "paginated_posts". That way you won't be limited to the paginated posts on the right hand side.

The more optimal way I would think of doing this is send the same # of posts per page as the max number you want to show for your "recent posts", assuming you are not trying to show ALL posts in your recent posts. If there is a happy medium for your most recent posts # to match the number of posts you want to paginate on - you are all set.

Upvotes: 1

Related Questions