Skip to content

Instantly share code, notes, and snippets.

@vitorfs
Last active October 14, 2016 07:59
Show Gist options
  • Save vitorfs/a47c3b7971a26fed71b65e3e34f76835 to your computer and use it in GitHub Desktop.
Save vitorfs/a47c3b7971a26fed71b65e3e34f76835 to your computer and use it in GitHub Desktop.
Django's paginator
from django.contrib.auth.models import User
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
def index(request):
# here is the list of elements you want to paginate.
user_list = User.objects.all()
# `page` is a parameter we will receive from the url, like this:
# http://127.0.0.1:8000/users/?page=1
# http://127.0.0.1:8000/users/?page=2
# It have two parameters, `page` and `1`, because the second one, is a default value
# in case there is no `page` variable in the url, like this:
# http://127.0.0.1:8000/users/
# Then in this case, the default page will be 1.
page = request.GET.get('page', 1)
# Here is where the paginating process being.
# We are creating a Paginator instance. We pass the list we want to paginate, that is, `user_list`
# And the number of elements per page. In this example we are using `10`.
paginator = Paginator(user_list, 10)
try:
# First we try to get the page the user requested.
# This is inside a try/except because this variable came from a GET parameter
# And it can contain a invalid value, like this:
# http://127.0.0.1:8000/users/?page=abc
# `abc` is not a int value, and it will break.
users = paginator.page(page)
except PageNotAnInteger:
# In case the user passed an invalid value in the `page` parameter, we fall back to page 1.
users = paginator.page(1)
except EmptyPage:
# And here is a last case of exception, where the user might have passed a valid int
# but it is too big, lets say:
# http://127.0.0.1:8000/users/?page=999
# since we don't have that many results (999 pages X 10 posts = 9990 posts)
# the page would be empty
# so in this case we fall back to the `last` page of the paginator, which is
# in `paginator.num_pages`
users = paginator.page(paginator.num_pages)
# after all the try/except, we can finally return to the template and render it.
# notice that we are not passing a QuerySet to the template, but, a Paginator (users)
# this paginator will contain only 10 elements (regardless of the size of your initial list)
# it will also contain the page you are at the moment, the other pages and so on.
return render(request, 'core/user_list.html', { 'users': users })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment