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})
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
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>
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)
thanks
Heads up I’m getting a 404 on your last “link for more info”
updated the link, thanks.
Tnx a lot :XXXXX