parts/django/docs/topics/pagination.txt
changeset 307 c6bca38c1cbf
equal deleted inserted replaced
306:5ff1fc726848 307:c6bca38c1cbf
       
     1 ==========
       
     2 Pagination
       
     3 ==========
       
     4 
       
     5 .. module:: django.core.paginator
       
     6    :synopsis: Classes to help you easily manage paginated data.
       
     7 
       
     8 .. versionchanged:: 1.0
       
     9    Pagination facilities have been almost fully reworked.
       
    10 
       
    11 Django provides a few classes that help you manage paginated data -- that is,
       
    12 data that's split across several pages, with "Previous/Next" links. These
       
    13 classes live in :file:`django/core/paginator.py`.
       
    14 
       
    15 Example
       
    16 =======
       
    17 
       
    18 Give :class:`Paginator` a list of objects, plus the number of items you'd like to
       
    19 have on each page, and it gives you methods for accessing the items for each
       
    20 page::
       
    21 
       
    22     >>> from django.core.paginator import Paginator
       
    23     >>> objects = ['john', 'paul', 'george', 'ringo']
       
    24     >>> p = Paginator(objects, 2)
       
    25 
       
    26     >>> p.count
       
    27     4
       
    28     >>> p.num_pages
       
    29     2
       
    30     >>> p.page_range
       
    31     [1, 2]
       
    32 
       
    33     >>> page1 = p.page(1)
       
    34     >>> page1
       
    35     <Page 1 of 2>
       
    36     >>> page1.object_list
       
    37     ['john', 'paul']
       
    38 
       
    39     >>> page2 = p.page(2)
       
    40     >>> page2.object_list
       
    41     ['george', 'ringo']
       
    42     >>> page2.has_next()
       
    43     False
       
    44     >>> page2.has_previous()
       
    45     True
       
    46     >>> page2.has_other_pages()
       
    47     True
       
    48     >>> page2.next_page_number()
       
    49     3
       
    50     >>> page2.previous_page_number()
       
    51     1
       
    52     >>> page2.start_index() # The 1-based index of the first item on this page
       
    53     3
       
    54     >>> page2.end_index() # The 1-based index of the last item on this page
       
    55     4
       
    56 
       
    57     >>> p.page(0)
       
    58     Traceback (most recent call last):
       
    59     ...
       
    60     EmptyPage: That page number is less than 1
       
    61     >>> p.page(3)
       
    62     Traceback (most recent call last):
       
    63     ...
       
    64     EmptyPage: That page contains no results
       
    65 
       
    66 .. note::
       
    67 
       
    68     Note that you can give ``Paginator`` a list/tuple, a Django ``QuerySet``, or
       
    69     any other object with a ``count()`` or ``__len__()`` method. When
       
    70     determining the number of objects contained in the passed object,
       
    71     ``Paginator`` will first try calling ``count()``, then fallback to using
       
    72     ``len()`` if the passed object has no ``count()`` method. This allows
       
    73     objects such as Django's ``QuerySet`` to use a more efficient ``count()``
       
    74     method when available.
       
    75 
       
    76 
       
    77 Using ``Paginator`` in a view
       
    78 ==============================
       
    79 
       
    80 Here's a slightly more complex example using :class:`Paginator` in a view to
       
    81 paginate a queryset. We give both the view and the accompanying template to
       
    82 show how you can display the results. This example assumes you have a
       
    83 ``Contacts`` model that has already been imported.
       
    84 
       
    85 The view function looks like this::
       
    86 
       
    87     from django.core.paginator import Paginator, InvalidPage, EmptyPage
       
    88 
       
    89     def listing(request):
       
    90         contact_list = Contacts.objects.all()
       
    91         paginator = Paginator(contact_list, 25) # Show 25 contacts per page
       
    92 
       
    93         # Make sure page request is an int. If not, deliver first page.
       
    94         try:
       
    95             page = int(request.GET.get('page', '1'))
       
    96         except ValueError:
       
    97             page = 1
       
    98 
       
    99         # If page request (9999) is out of range, deliver last page of results.
       
   100         try:
       
   101             contacts = paginator.page(page)
       
   102         except (EmptyPage, InvalidPage):
       
   103             contacts = paginator.page(paginator.num_pages)
       
   104 
       
   105         return render_to_response('list.html', {"contacts": contacts})
       
   106 
       
   107 In the template :file:`list.html`, you'll want to include navigation between
       
   108 pages along with any interesting information from the objects themselves::
       
   109 
       
   110     {% for contact in contacts.object_list %}
       
   111         {# Each "contact" is a Contact model object. #}
       
   112         {{ contact.full_name|upper }}<br />
       
   113         ...
       
   114     {% endfor %}
       
   115 
       
   116     <div class="pagination">
       
   117         <span class="step-links">
       
   118             {% if contacts.has_previous %}
       
   119                 <a href="?page={{ contacts.previous_page_number }}">previous</a>
       
   120             {% endif %}
       
   121 
       
   122             <span class="current">
       
   123                 Page {{ contacts.number }} of {{ contacts.paginator.num_pages }}.
       
   124             </span>
       
   125 
       
   126             {% if contacts.has_next %}
       
   127                 <a href="?page={{ contacts.next_page_number }}">next</a>
       
   128             {% endif %}
       
   129         </span>
       
   130     </div>
       
   131 
       
   132 
       
   133 ``Paginator`` objects
       
   134 =====================
       
   135 
       
   136 The :class:`Paginator` class has this constructor:
       
   137 
       
   138 .. class:: Paginator(object_list, per_page, orphans=0, allow_empty_first_page=True)
       
   139 
       
   140 Required arguments
       
   141 ------------------
       
   142 
       
   143 ``object_list``
       
   144     A list, tuple, Django ``QuerySet``, or other sliceable object with a
       
   145     ``count()`` or ``__len__()`` method.
       
   146 
       
   147 ``per_page``
       
   148     The maximum number of items to include on a page, not including orphans
       
   149     (see the ``orphans`` optional argument below).
       
   150 
       
   151 Optional arguments
       
   152 ------------------
       
   153 
       
   154 ``orphans``
       
   155     The minimum number of items allowed on the last page, defaults to zero.
       
   156     Use this when you don't want to have a last page with very few items.
       
   157     If the last page would normally have a number of items less than or equal
       
   158     to ``orphans``, then those items will be added to the previous page (which
       
   159     becomes the last page) instead of leaving the items on a page by
       
   160     themselves. For example, with 23 items, ``per_page=10``, and
       
   161     ``orphans=3``, there will be two pages; the first page with 10 items and
       
   162     the  second (and last) page with 13 items.
       
   163 
       
   164 ``allow_empty_first_page``
       
   165     Whether or not the first page is allowed to be empty.  If ``False`` and
       
   166     ``object_list`` is  empty, then an ``EmptyPage`` error will be raised.
       
   167 
       
   168 Methods
       
   169 -------
       
   170 
       
   171 .. method:: Paginator.page(number)
       
   172 
       
   173     Returns a :class:`Page` object with the given 1-based index. Raises
       
   174     :exc:`InvalidPage` if the given page number doesn't exist.
       
   175 
       
   176 Attributes
       
   177 ----------
       
   178 
       
   179 .. attribute:: Paginator.count
       
   180 
       
   181     The total number of objects, across all pages.
       
   182 
       
   183     .. note::
       
   184 
       
   185         When determining the number of objects contained in ``object_list``,
       
   186         ``Paginator`` will first try calling ``object_list.count()``. If
       
   187         ``object_list`` has no ``count()`` method, then ``Paginator`` will
       
   188         fallback to using ``object_list.__len__()``. This allows objects, such
       
   189         as Django's ``QuerySet``, to use a more efficient ``count()`` method
       
   190         when available.
       
   191 
       
   192 .. attribute:: Paginator.num_pages
       
   193 
       
   194     The total number of pages.
       
   195 
       
   196 .. attribute:: Paginator.page_range
       
   197 
       
   198     A 1-based range of page numbers, e.g., ``[1, 2, 3, 4]``.
       
   199 
       
   200 ``InvalidPage`` exceptions
       
   201 ==========================
       
   202 
       
   203 The ``page()`` method raises ``InvalidPage`` if the requested page is invalid
       
   204 (i.e., not an integer) or contains no objects. Generally, it's enough to trap
       
   205 the ``InvalidPage`` exception, but if you'd like more granularity, you can trap
       
   206 either of the following exceptions:
       
   207 
       
   208 ``PageNotAnInteger``
       
   209     Raised when ``page()`` is given a value that isn't an integer.
       
   210 
       
   211 ``EmptyPage``
       
   212     Raised when ``page()`` is given a valid value but no objects exist on that
       
   213     page.
       
   214 
       
   215 Both of the exceptions are subclasses of ``InvalidPage``, so you can handle
       
   216 them both with a simple ``except InvalidPage``.
       
   217 
       
   218 
       
   219 ``Page`` objects
       
   220 ================
       
   221 
       
   222 .. class:: Page(object_list, number, paginator)
       
   223 
       
   224 You usually won't construct :class:`Pages <Page>` by hand -- you'll get them
       
   225 using :meth:`Paginator.page`.
       
   226 
       
   227 
       
   228 Methods
       
   229 -------
       
   230 
       
   231 .. method:: Page.has_next()
       
   232 
       
   233     Returns ``True`` if there's a next page.
       
   234 
       
   235 .. method:: Page.has_previous()
       
   236 
       
   237     Returns ``True`` if there's a previous page.
       
   238 
       
   239 .. method:: Page.has_other_pages()
       
   240 
       
   241     Returns ``True`` if there's a next *or* previous page.
       
   242 
       
   243 .. method:: Page.next_page_number()
       
   244 
       
   245     Returns the next page number. Note that this is "dumb" and will return the
       
   246     next page number regardless of whether a subsequent page exists.
       
   247 
       
   248 .. method:: Page.previous_page_number()
       
   249 
       
   250     Returns the previous page number. Note that this is "dumb" and will return
       
   251     the previous page number regardless of whether a previous page exists.
       
   252 
       
   253 .. method:: Page.start_index()
       
   254 
       
   255     Returns the 1-based index of the first object on the page, relative to all
       
   256     of the objects in the paginator's list. For example, when paginating a list
       
   257     of 5 objects with 2 objects per page, the second page's :meth:`~Page.start_index`
       
   258     would return ``3``.
       
   259 
       
   260 .. method:: Page.end_index()
       
   261 
       
   262     Returns the 1-based index of the last object on the page, relative to all of
       
   263     the objects in the paginator's list. For example, when paginating a list of
       
   264     5 objects with 2 objects per page, the second page's :meth:`~Page.end_index`
       
   265     would return ``4``.
       
   266 
       
   267 Attributes
       
   268 ----------
       
   269 
       
   270 .. attribute:: Page.object_list
       
   271 
       
   272     The list of objects on this page.
       
   273 
       
   274 .. attribute:: Page.number
       
   275 
       
   276     The 1-based page number for this page.
       
   277 
       
   278 .. attribute:: Page.paginator
       
   279 
       
   280     The associated :class:`Paginator` object.
       
   281