Paginating Vaccine Views
In this video, we will learn how to paginate Vaccine List view of vaccine app. We have already disccused how to paginate function based view. Today we will be learning how to paginate any class based view.
Views
At first, open your views.py file of vaccine and navigate to the VaccineList view.
In the get method, At first, we need to order the queryset.
vaccine_list = Vaccine.objects.all().order_by("name")
Here we are ordering the vaccine list by their name in alphebetical order.
Now, import the Paginator class
from django.core.paginator import Paginator
After that, create a paginator object with vaccine list queryset. As of now, we will paginate queryset by 2 objects per page.
paginator = Paginator(vaccine_list, 2)
After that, grab the page number from the query params.
page_number = request.GET.get("page")
Then generate the page obj for that page number
page_obj = paginator.get_page(page_number)
Now, add this page_obj in the context.
context = {
"page_obj": page_obj,
}
Templates
Open the vaccine list template.
Here we will iterate through the page_obj
{% for vaccine in page_obj %}
After that, we will include the pagination component that contains links to first page, last page and other page numbers.
{% include "components/pagination.html" %}
[Run the development server and see the changes]
In this way, we have learnt how to paginate any class based view in django.