DEV Community

Cover image for How to Paginate with Django?
Biplov
Biplov

Posted on • Updated on

How to Paginate with Django?

Pagination is a common navigation technique of dividing content into discrete pages. It helps make the content more organized, and thus improving user experience.

So, how do we paginate data in Django?
First thing we need to do is update our views to paginate the data.
We will look at both Function-Based Views and Class-Based Views.

Function-Based View

We need to import paginator from django.core.paginator which splits a Query-Set into Page objects.
Consider we have 45 blog posts and we want to display at most 10 posts per page.

from django.shortcuts import render
from django.core.paginator import Paginator
form .models import Blog

def blogposts(request):
    blogs = Blog.objects.all()
    paginator = Paginator(blogs, 10)

    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    return render(request, 'index.html', {'page_obj': page_obj})


Enter fullscreen mode Exit fullscreen mode

The above example will Paginate the blogs Query-Set in pages of 10. This will create a 5 pages result. The first 4 pages with 10 blog posts each and the last page with 5.

Class-Based View

In class based views we can use paginate_by attribute to specify the number by which to paginate the queryset.

from .models import Blog
from django.views.generic import ListView

class blogposts(ListView):
    model = Blog
    paginate_by = 10
Enter fullscreen mode Exit fullscreen mode

Template

After updating the views we need to update our template.
To be able to navigate between posts we need to add links in our template.

<!--
 code to display blog posts ...
-->
<div class="pagination">
    <span class="step-links">
        {% if page_obj.has_previous %}          
            <a href="?page={{ page_obj.previous_page_number }}">previous</a>
        {% endif %}

        <span class="current">
          {{ page_obj.number }}
        </span>

        {% if page_obj.has_next %}
            <a href="?page={{ page_obj.next_page_number }}">next</a>
        {% endif %}
    </span>
</div>

Enter fullscreen mode Exit fullscreen mode

This displays a previous-next links with current page number.


This is a simple example of pagination but you can get more creative with it. You can follow this link for more information about Paginator class.

Top comments (4)

Collapse
 
salahdev profile image
Salah DzCoder

thanks

Collapse
 
benhammondmusic profile image
Ben Hammond

Heads up I’m getting a 404 on your last “link for more info”

Collapse
 
biplov profile image
Biplov

updated the link, thanks.

Collapse
 
alimp5 profile image
alimp5

Tnx a lot :XXXXX