Search code examples
djangodjango-paginationdjango-viewflow

paginator function not working in django?


My issue is that i want to retrieve only 6 objects per page but its showing all 10 per page

my view

def home(request):
    if request.method == 'GET':

        entry = Entry.objects.all().order_by('date_added')
        # top_rated = Entry.objects.annotate(
        #     no_of_likes=Count('likes')).order_by('-no_of_likes')[:2]
        pages = Paginator(entry, 6)

        if request.GET.get('page'):
            print('executed')
            page_num = request.GET.get('page')
            pages = pages.page(page_num)

        entries = pages.object_list
    print(len(entries))
    return render(request, 'base/base.html', {'entries': entries,
                                              'pages': pages})

Solution

  • You have written the code in a fashion with redundant / incomplete (unhandled) checks and assigning different objects to the same variable, resulting in the problem you see. Basically what is happening is that your condition if request.GET.get('page'): evaluates to False likely because page is not present in the query string. This means entries = pages.object_list gives you your complete queryset.

    Instead try something like follows:

    def home(request):
        entry = Entry.objects.all().order_by('date_added')
        pages = Paginator(entry, 6)
        page_number = request.GET.get('page')
        page = paginator.get_page(page_number)
        entries = page.object_list
        return render(request, 'base/base.html', {'entries': entries, 'page': page})