Django Implementation of Infinite Scroll with HTMX
I have also included Bootstrap for styling, but it’s optional.
git clone https://github.com/andgineer/django-htmx-infinite-scroll.git
. ./activate # Note the dot at the beginning of the command
Now, open http://localhost:8000/ in your browser to view our infinite scroll list, which loads more pages as you scroll.
How to Create Such an Application in Five Minutes
Create a Django Application
You should have Python and pip installed.
Install Django and create a project named
core and an app named
Add the app to INSTALLED_APPS in
Create a Model
Create a model in
django_htmx_infinite_scroll/models.py similar to BookPage.
Now, Django is aware of our model and can create a database table:
Populate the Database
To test, create records in the database. To do this, we need a Django command - add the contents of add-pages.py
Now you can run
python manage.py add-pages.
Define two views in
django_htmx_infinite_scroll/views.py, which can be copied from views.py.
To access these views, we need to add URLs.
Add a link to the app’s URL in core/urls.py:
The first URL will invoke the book view, which displays book pages. The second URL will serve book pages, both for the initial display of the first pages and for loading the next book page via HTMX as you scroll.
We are almost done. Now, create templates for our views.
We will create a template hierarchy to avoid duplicating code.
Copy the files from templates/
Start the Server
Now you can start the server and see the result:
Open http://localhost:8000/ in your browser, and you will see a scrollable list of pages.
HTMX infinite scroll
To show one page we use the code above.
It includes a
hx-get attribute to specify the URL for an AJAX request.
It call our view
book_page with the page number as a parameter.
hx-swap attribute defines where the response should be inserted.
afterend means that the response will
be inserted after the current element.
hx-trigger attribute specifies the event that triggers the AJAX request.
revealed means that the request
will be sent when the element becomes visible.
So when the user scrolls down and the page becomes visible, HTMX will send an AJAX request to Django to get the next page. And so on.
Integrating HTMX Library
In the book template, we specify this base template: