Django’s Pagination allows you to handle data divided across several pages using “Previous” and “Next” links.
The Paginator class takes in a queryset (such as a Django model) and splits it into Page objects that are then displayed across these pages while still using the same HTML document.
Pagination works well for listing articles, products, and/or charts and is easy to implement on your template pages. Connect the Paginator class to a views function then call the Pagination class attribute in the template and Django Pagination will handle generating the pages as needed.
#env > mysite > main > views.py
from django.shortcuts import render
from .models import Movie
# Create your views here.
def movies(request):
movies = Movie.objects.all() #queryset containing all movies we just created
return render(request=request, template_name="main/movies.html", context={'movies':movies})
We will be using the Movie model from the tutorial How to use Django Models. Above is how the view function looked at the end of the tutorial.
...
from django.core.paginator import Paginator #import Paginator
def movies(request):
movies = Movie.objects.all() #queryset containing all movies we just created
paginator = Paginator(movies, 3)
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
return render(request=request, template_name="main/movies.html", context={'movies':page_obj})
Start by importing Paginator
at the top of the page. Then add three new variables to the movies function.
First, create a paginator
object with the Paginator
class. As arguments pass in the movies queryset and number of movies per page, 3. Then create a page_number
variable that requests the current page number. Next, combine all of the data into page_obj
.
Finally, we need to set the context movies
to equal page_obj
before moving on to the template. That way all of the models fields called in the template can still be called using the context movies but with all of the pagination functionality.
#django #django-web-framework #pagination #bootstrap #python