Django 1.8 official document translation: 13-6 pages



Django provides classes to help you manage paged data — that is, data is divided into different pages with a “previous / next” tag. These classes are located indjango/core/paginator.pyIn the middle.


towardsPaginatorProvide a list of objects and the number of elements you want to assign to each page. It will provide you with a way to access the objects on each page

>>> from django.core.paginator import Paginator
>>> objects = ['john', 'paul', 'george', 'ringo']
>>> p = Paginator(objects, 2)

>>> p.count
>>> p.num_pages
>>> p.page_range
[1, 2]

>>> page1 =
>>> page1
<Page 1 of 2>
>>> page1.object_list
['john', 'paul']

>>> page2 =
>>> page2.object_list
['george', 'ringo']
>>> page2.has_next()
>>> page2.has_previous()
>>> page2.has_other_pages()
>>> page2.next_page_number()
Traceback (most recent call last):
EmptyPage: That page contains no results
>>> page2.previous_page_number()
>>> page2.start_index() # The 1-based index of the first item on this page
>>> page2.end_index() # The 1-based index of the last item on this page

Traceback (most recent call last):
EmptyPage: That page number is less than 1
Traceback (most recent call last):
EmptyPage: That page contains no results

be careful

Note that you can askPaginatorProvide a list or tuple, Django’sQuerySetOr anything withcount()or__len__()Method. When calculating the number of objects contained in an incoming object,PaginatorWill try to call thecount(), and then if the incoming object does notcount()Methodlen(). This will make Django likeQuerySetUsing more efficientcount()Methods, if they exist.


Here are a few more complex examples that are used in the viewPaginatorTo page the query set. We provide views and related templates to show how to present these results. This example assumes that you have an importedContactsModel.

The view function looks like this:

from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

def listing(request):
    contact_list = Contacts.objects.all()
    paginator = Paginator(contact_list, 25) # Show 25 contacts per page

    page = request.GET.get('page')
        contacts =
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        contacts =
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        contacts =

    return render_to_response('list.html', {"contacts": contacts})

staylist.htmlIn the template, you want to include navigation between pages, as well as any interesting information from the object itself:

<div class="pagination">
    <span class="step-links">

        <span class="current">
            Page  of .


Paginator objects

PaginatorClass has the following constructors:

_class _Paginator(_object_list_, _per_page_, _orphans=0_, _allow_empty_first_page=True_)[source]

Required parameters


A list, tuple, Django QuerySet, or other sliceable object with a
count() or __len__() method.


The maximum number of items to include on a page, not including orphans
(see the orphans optional argument below).

Optional parameters


The minimum number of items allowed on the last page, defaults to zero.
Use this when you don’t want to have a last page with very few items.
If the last page would normally have a number of items less than or equal
to orphans, then those items will be added to the previous page (which
becomes the last page) instead of leaving the items on a page by
themselves. For example, with 23 items, per_page=10, and
orphans=3, there will be two pages; the first page with 10 items and
the second (and last) page with 13 items.


Whether or not the first page is allowed to be empty. If False and
object_list is empty, then an EmptyPage error will be raised.



Returns the value at the provided subscriptPageObject, subscript starts with 1. If the page number provided does not exist, theInvalidPageAbnormal.



The total number of objects for all pages.

be careful

When calculatingobject_listThe number of objects contained,PaginatorWill try to call theobject_list.count(). Ifobject_listNo,count()method,PaginatorThen it goes back to uselen(object_list). This makes it similar to Django’sQuerySetMore convenient to usecount()Methods, if they exist.


Total number of pages.


The range of page numbers, starting from 1, e.g[1, 2, 3, 4]

InvalidPage exceptions

_exception _InvalidPage[source]

Exception, thrown when Paginator passes in an invalid page number. back to throw an exception when the requested page is invalid (such as not an integer) or does not contain any objects. In general, captureInvalidPageExceptions are enough, but if you want to be more elaborate, you can catch one of the following two exceptions:

_exception _PageNotAnInteger[source]

When topage()Thrown when a value other than an integer is provided.

_exception _EmptyPage[source]

When topage()It is thrown when a valid value is provided, but there is no object on that page.

Both of these are exceptionsInvalidPageSo you can use simpleexcept InvalidPageTo deal with them.

Page objects

You don’t usually need to build manuallyPageObjects – you can choose get them.

_class _Page(_object_list_, _number_, _paginator_)[source]

When callinglen()Or when you iterate directly over a page, its behavior is similar toPage.object_listSequence of.



Returns True if there’s a next page.


If there is a previous page, return toTrue


If there is a previous page_ Or_ Next page, back toTrue


Returns the page number of the next page. If the next page does not exist, throwInvalidPageAbnormal.


Returns the page number of the previous page. If the previous page does not exist, throwInvalidPageAbnormal.


Returns the first object on the current page, relative to the sequence number of all objects in the paging list, starting from 1. For example, divide the list of five objects into two objects on each page, and the list of objects on the second pagestart_index()Will return3


Returns the last object on the current page, relative to the sequence number of all objects in the paging list, starting from 1. For example, divide the list of five objects into two objects on each page, and the list of objects on the second pageend_index()Will return4



A list of all objects on the current page.


The serial number of the current page, starting from 1.



translator:Django document collaborative translation teamOriginal text:Pagination

This paper is based onCC BY-NC-SA 3.0Please keep the author’s signature and the source of the article.

Django document collaborative translation teamWe are short of staff. Interested friends can join us. It is totally public welfare. Communication group: 467338606.