Search code examples
pythondjangoajaxpaginationdjango-pagination

Why does my django pagination keeps returning the same items infinitely?


I am using django and ajax to create a infinite scroll on my website. I would like it to load more items from the database (that are in the next page) when the user scrolls to the bottom of the page. Everything is working perfectly except that it keeps returning the first page's items infinitely. For example if a user scrolls down to the end of a page instead of adding page 2's elements it just add the same elements from the first page to the bottom again. I am very sure this issue is from my views.py. I can't seem to figure out what's wrong.

def feed(request):
    queryset2 = Store_detail.objects.filter(store_lat__gte=lat1, store_lat__lte=lat2)\
    .filter(store_lng__gte=lng1, store_lng__lte=lng2)
queryset3 = Paginator(queryset2, 4)
    page = request.GET.get('page',1)
    try:
         queryset = queryset3.page(1)
    except PageNotAnInteger:
        queryset = queryset3.page(page)
    except EmptyPage:
        queryset = ""
    context = {
        "location":location,
        "queryset":queryset,
    }
    # return HttpResponse(template.render(context,request))
    return render(request, 'main/feed.html', {'queryset': queryset, 
'location':location,})

So basically I would like to load the next page when a user scrolls to the end of the screen and if there are no more items in the next page or the next page does not exist then stop adding items.


Solution

  • The pagination logic is a bit off. You paginate with:

    try:
        # you first try to retrieve page 1
        queryset = queryset3.page(1)
    except PageNotAnInteger:
        queryset = queryset3.page(page)
    except EmptyPage:
        queryset = ""

    This thus means that you first aim to fetch the first page, and only if 1 is not an integer, you will fetch a page with the page querystring parameter. You should swap these, like:

    try:
        queryset = queryset3.page(page)
    except PageNotAnInteger:
        queryset = queryset3.page(1)
    except EmptyPage:
        queryset = Store_detail.objects.none()