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.
Dependencies
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:
base.html
Basic Example
This example uses function-based view and I’m simply paginating a list of numbers, which I generate on the fly.
urls.py
views.py
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:
blog/home.html
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
.infinite-more-link.
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.
blog/home.html
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:
models.py
views.py
blog/articles.html
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.