Django Pagination
Pagination allows us to distribute iterable content over multiple pages. We can then navigate to these pages with the page number of the previous page and next page buttons.
Paginator Class and Page Object
Django offers a Paginator class with attributes such as:
- page(page_number): Returns page_object with given page_number
- has_previous: True/False if previous page number exists
- has_next: True/False if previous next number exists
- previous_page_number: Returns previous page number
- next_page_number: Returns next page number
- number: Returns current page number
- paginator.num_pages: Returns total page numbers
Firstly, import the Paginator class.
from django.core.paginator import Paginator
Now, select number of objects per page.
p = Paginator(queryset, number_of_objects_per_page)
Then, make page object with page() function.
page_object = p.page(page_number)
In order to get page number from URL request use:
page_object = p.page(request.GET.get('page'))
Lastly, return the page_object as a context variable. The combined code under views.py will look as below:
from django.core.paginator import Paginator
def my_view_function(request):
queryset = ['A', 'B', 'C', 'D', 'E'] # sample data
p = Paginator(queryset, 1) # for 1 object per page
try:
page_number = request.GET.get('page')
page_object = p.page(page_number)
except:
page_object = p.page(1) # load first page by default
return render(request, 'my_template.html', {'page_object':page_object})