#

Django Pagination Steps

Oct. 24, 2022
Author: Asif Shahzad | Full Stack Web Developer


 In Pagination technique, we break a big data to multiple pages that improves the user experience and speed of loading. Django provides a Paginator class for this purpose. The easiest way for this task is expalined here.   

Add at the top of views.py

from django.core.paginator import Paginator,EmptyPage, PageNotAnInteger

In blog function add this code:

def blog(request):
    posts = Post.objects.all()  # fetching all posts
    p = Paginator(posts, 5)  # creating a paginator object
    page_number = request.GET.get('page')  # getting the desired page number from url
    try:
        page_obj = p.get_page(page_number)  # returns the desired page object
    except PageNotAnInteger:
        # if page_number is not an integer then assign the first page
        page_obj = p.page(1)
    except EmptyPage:
        # if page is empty then return last page
        page_obj = p.page(p.num_pages)

    return render(request, 'index.html', {'page_obj': page_obj})

Now in template add this:

{% for x in page_obj.object_list %}
    # your content should be here--------------------      
       <p>{{x.title}}</p>    
{% endfor %}

# Your pagination at the bottom------------------------
        {%if page_obj.has_previous %} {# whether the previous page exists #}
            <a href="?page={{page_obj.previous_page_number}}"><</a> {# link to the prev page #}
        {% endif %}
        <span>{{page_obj.number}}</span> {# the current page number #}
        
        {%if page_obj.has_next %} {# whether the next page exists #}
            <a href="?page={{page_obj.next_page_number}}">></a> {# link to the next page #}
        {% endif %}
   

The final page is here:

Please share this page to friends.

Asif Shahzad | Full Stack Web Developer

We have expertise in website designing & development, software solutions, mobile app development, e-commerce solutions and graphic designing. We transform your visions into reality by providing 24/7 services.

Popular Posts

Call To Action

Do you Need a website?

Order Now