In this tutorial I will show you how to implement a very simple infinite scrolling with Django. Basically we will
take advantage of Django’s pagination API and a jQuery plug-in. You will find examples using both function-based views
and class-based views.
We don’t need anything other than Django installed in the back-end. For this example you will need jQuery and Waypoints.
After downloading the dependencies, include the following scripts in your template:
This example uses function-based view and I’m simply paginating a list of numbers, which I generate on the fly.
Here in this view, numbers_list represents a list of 1000 numbers, which I’m breaking down into blocks of 20 numbers
per page. After paginating it, I return the numbers object to the template, which is a block of 20 numbers.
I won’t get into details about Django pagination because I have an article talking exclusively about it, so if you want
to learn more, check this post: How to Paginate with Django.
Now here is where the magic happens:
The element identified by the class .infinite-container is the container where the plug-in will load more items. This
action will occur every time the element .infinite-more-link appears in the screen. When that happens, it will
trigger an asynchronous request (AJAX) loading the content from the URL specified in the href of the
The page will keep loading new items until the .infinite-more-link is no longer shown. It will happen when there is
no more items to be loaded. That is, the paginator reached the last page.
That’s why we have the conditional if numbers.has_next.
Adding Loading State
We can improve the basic example by adding a loading state, while the page is grabbing more data.
Our loading block will be shown while the AJAX is running in the background:
Class-Based View Example With Models
The idea remain the same. Actually, the example will become even cleaner. Consider the following model:
Just a small difference here, that since I’m using a ListView, the page object is available in the page_obj object
in the template.