Create endless pagination with Django and AJAX
Hi Devs! Today I am going to show you quick tutorial about how to create endless pagination or infinite scroll with Django
There are many sources on internet related with this topic but majority of them are not fully explained. So, I will try to explain it clearly and step by step for you.
Alright! Let's launch our infinite-scroll-django rocket!
I am assuming that you already created your project
Step 1: Creating our model
We are going to create very simple blog with posts. Let's create our post model in models.py
Don't forget to migrate your model :)
Step 2: Creating our view
In views.py we are going to import ListView, it is a class-based view and it will contain the list of objects.
As you see I will load 2 posts per scroll by using paginate_by attribute but you can change it how many you want. The context_object_name attribute specifies the name of variable to access from templates. Providing a useful context_object_name is always a good idea. Your coworkers who design templates will thank you. In addition, you can order posts by title or published date but for now let's keep it title.
Step 3: URL Configuration
Time to configure our urls.py, so let's see the code first.
In class-based views, you have to call as_view() function so as to return a callable view that takes a request and returns a response. Its the main entry-point in request-response cycle in case of generic views.
Just reminder static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) is for serving media files.
Step 4: Waypoints JS and Template
Waypoints is a small jQuery plugin that makes it easy to execute a function whenever you scroll to an element.
Alright! Let's see the code first
This is the main part of tutorial, we are first including jquery-2.2.4.min.js. It is better to include 2.2.4 version of jQuery otherwise it will cause errors. Then add jquery.waypoints.min.js and infinite.min.js
You can get scripts from directly github repo of waypoints.jquery.waypoints.min.js infinite.min.js
element option for Infinite referes to the container around all infinite items that will be used as the waypoint and fetched items will be appended to.
.infinite-more-link is matching the "Next Page" element on every page.
.infinite-item is a selector string that should match the individual items that will be pulled out of each page and appended to the item container.
offset is the same offset option from a regular Waypoint, except the default is now 'bottom-in-view' instead of 0. This means, by default, new items will be loaded when the bottom of the container comes into view.
PageLoad functions is for display spinner while posts are loading
You just learned something very useful today and launched your infinite-scroll-django rocket! You can clone or download this project from my git repository and don't forget to follow me on social media, join Reverse Astronauts community!