Lazy Load Script Django.How

Author avatar wrote on 26/05/2022

For example i will use news app.

To install Lazy Load script first of all need to import some django modules. In views.py add 2 rows on the top:


from django.http import JsonResponse
from django.template.loader import render_to_string


2.In page function, before return, we need to make check if request ask for lazy load or not.


if request.method == "GET" and "lazy_load" in request.GET:
    lazy_html = render_to_string('news/parts/_list.html', context, request)
    return JsonResponse({'html':lazy_html})
else:
    return render(request, 'news/index.html', context)

This page must have pagination!!!

Prepare html template. List of news must be in another file without conection of header and footer. In this example i made file ‘_list.html’:

Important to remember - container of news list must be not in this file but “Show More“ link must be in.

In this way we will not recieve container with same id we have and we can update “Show More“ link after each request.

index.html of news app will be like this

4.Show More“ link can be any element. Important only to set onclick function (or other like - onsubmit, onhover, etc.) with 3 parametrs - lazyLoadFunc(url, containerId, linkContainerId):

1 - URL of next page.

2 - Id of news list container

3 - Id of 'show more' link container

JS file.

Do not forget to include it in base.html file.

CRUDgen Django CRUD generator