Fixed #9215 -- Added a view/template example of using pagination.

Based on a patch from shacker and Matt Dennenbaum.


git-svn-id: http://code.djangoproject.com/svn/django/trunk@9193 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Malcolm Tredinnick 2008-10-07 11:51:14 +00:00
parent 08c3ad0cd0
commit 72f387d344
2 changed files with 84 additions and 26 deletions

View File

@ -107,6 +107,7 @@ answer newbie questions, and generally made Django that much better:
Jason Davies (Esaj) <http://www.jasondavies.com/>
Richard Davies <richard.davies@elastichosts.com>
Alex Dedul
Matt Dennenbaum
deric@monowerks.com
Max Derkachev <mderk@yandex.ru>
Rajesh Dhawan <rajesh.dhawan@gmail.com>

View File

@ -75,6 +75,63 @@ page::
objects such as Django's ``QuerySet`` to use a more efficient ``count()``
method when available.
Using ``Paginator`` in a view
==============================
Here's a slightly more complex example using :class:`Paginator` in a view to
paginate a queryset. We give both the view and the accompanying template to
show how you can display the results. This example assumes you have a
``Contacts`` model that has already been imported.
The view function looks like this::
from django.core.paginator import Paginator, InvalidPage, EmptyPage
def listing(request):
contact_list = Contacts.objects.all()
paginator = Paginator(contact_list, 25) # Show 25 contacts per page
# Make sure page request is an int. If not, deliver first page.
try:
page = int(request.GET.get('page', '1'))
except ValueError:
page = 1
# If page request (9999) is out of range, deliver last page of results.
try:
contacts = paginator.page(page)
except (EmptyPage, InvalidPage):
contacts = paginator.page(paginator.num_pages)
return render_to_response('list.html', {"contacts": contacts})
In the template :file:`list.html`, you'll want to include navigation between
pages along with any interesting information from the objects themselves::
{% for contact in contacts.object_list %}
{# Each "contact" is a Contact model object. #}
{{ contact.full_name|upper }}<br />
...
{% endfor %}
<div class="pagination">
<span class="step-links">
{% if contacts.has_previous %}
<a href="?page={{ contacts.previous_page_number }}">previous</a>
{% endif %}
<span class="current">
Page {{ contacts.number }} of {{ contacts.paginator.num_pages }}.
</span>
{% if contacts.has_next %}
<a href="?page={{ contacts.next_page_number }}">next</a>
{% endif %}
</span>
</div>
``Paginator`` objects
=====================