How to load more data on a button click in Django

Anshu Pal
2 min readOct 3, 2021

In this article, we will learn how to create endless pagination or load more data on a button click. Loading all the data at once is not a good option, imagine if you have thousands of gigabytes of data and you are loading it simultaneously, not only it will load slowly but also decrease the overall user experience.

So it’s always a good idea to load the data in small chunks and if the user wants to see more, then load more data.

youtube tutorial

Project Setup

Create a basic model with title and description field and register the model

from django.db import models 
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=50)
desc = models.CharField(max_length=300, blank=True, null=True)
def __str__(self) -> str:
return self.title

Now simply create a function in your views.py to render the data in your HTML file.

from myapp.models import Post
from django.shortcuts import render
from django.http import JsonResponse

# Create your views here.
def index(request):
post_obj = Post.objects.all()[0:5]
total_obj = Post.objects.count()
return render(request, 'index.html', context={'posts': post_obj, 'total_obj': total_obj})

Let say we have a total of 10 objects in our model, so in the index function, we are only rendering 5 and the rest will be rendered when the user wants them to be rendered.

Now create an HTML file and send an ajax request for loading more posts.

Here on click of “loadBtn”, the loadmorePost() function is called to load more posts.

Now create a function to handle this request.

def load_more(request):    
loaded_item = request.GET.get('loaded_item')
loaded_item_int = int(offset)
limit = 2
post_obj = list(Post.objects.values() [loaded_item_int:loaded_item_int+limit])
data = {'posts': post_obj}
return JsonResponse(data=data)

For Demo of the Project visit youtube channel

Here in this function loaded_item are the number of items that are already loaded and the limit is the number of item to be loaded after a button click.

for a complete and detailed tutorial visit youtube

Github Code

Follow me on Medium and Github for more

Happy Coding!!!

Cheers!!!

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Anshu Pal
Anshu Pal

Written by Anshu Pal

I’m a web developer. I spend my whole day, practically every day, experimenting with HTML, CSS, and JavaScript.

No responses yet

Write a response