Posted under » Django on 5 Jun 2021
Django provides high-level and low-level ways to help you manage paginated data – that is, data that’s split across several pages, with “Previous/Next” links.
django.views.generic.list.ListView provides a builtin way to paginate the displayed list. You can do this by adding a paginate_by attribute to your view class, for example
from django.views.generic import ListView from myapp.models import Contact class ContactListView(ListView): paginate_by = 2 model = Contact
You can also use Paginator in a view function.
from django.core.paginator import Paginator from myapp.models import Contact def listing(request): contact_list = Contact.objects.all() paginator = Paginator(contact_list, 25) # Show 25 contacts per page. page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, 'list.html', {'page_obj': page_obj})
Here is how the template may look like.
{% for contact in page_obj %} {# Each "contact" is a Contact model object. #} {{ contact.full_name|upper }}<br> ... {% endfor %} <div class="pagination"> <span class="step-links"> {% if page_obj.has_previous %} <a href="?page=1">« first</a> <a href="?page={{ page_obj.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}. </span> {% if page_obj.has_next %} <a href="?page={{ page_obj.next_page_number }}">next</a> <a href="?page={{ page_obj.paginator.num_pages }}">last »</a> {% endif %} </span> </div>