Code

Ticket #9215: pagination.diff

File pagination.diff, 2.2 KB (added by shacker, 6 years ago)

Formatting corrections to original patch

Line 
1Index: docs/topics/pagination.txt
2===================================================================
3--- docs/topics/pagination.txt  (revision 9084)
4+++ docs/topics/pagination.txt  (working copy)
5@@ -75,6 +75,62 @@
6     objects such as Django's ``QuerySet`` to use a more efficient ``count()``
7     method when available.
8 
9+
10+Implementation Example
11+======================
12+
13+A working example of a view and accompanying template might look like this,
14+assuming you want to display a multi-page listing of an existing "Contacts"
15+model:
16+
17+In :file:`views.py`: ::
18+
19+    from django.core.paginator import Paginator, InvalidPage, EmptyPage
20+
21+    def listing(request):
22+        contact_list = Contacts.objects.all()
23+        paginator = Paginator(contact_list, 25) # Show 25 contacts per page
24+
25+        # Make sure page request is an int. If not, deliver first page.
26+        try:
27+            page = int(request.GET.get('page', '1'))
28+        except ValueError:
29+            page = 1
30+       
31+        # If page request (9999) is out of range, deliver last page of results.
32+        try:
33+            contacts = paginator.page(page)
34+        except (EmptyPage, InvalidPage):
35+            contacts = paginator.page(paginator.num_pages)
36+
37+        return render_to_response(
38+            'list.html',
39+            locals(),
40+            context_instance=RequestContext(request)
41+        )
42+
43+In template :file:`list.html`, you'll want navigation between pages.
44+Note that you can simply output the page object as ``{{ contacts }}`` to
45+render the "page *n* of pages" information.::
46+
47+    {% for contact in contacts.object_list %}
48+        {{ contact.full_name|upper }}<br />
49+        ...
50+    {% endfor %}
51+
52+    <div class="pagination">
53+        <span class="step-links">
54+        {% if contacts.has_previous %}<a href="?page={{ contacts.previous_page_number }}"
55+            class="util-link">previous</a>{% endif %}
56+        <span class="current">
57+            {{ contacts }}
58+        </span>
59+        {% if contacts.has_next %}<a href="?page={{ contacts.next_page_number }}"
60+            class="util-link">next</a>{% endif %}
61+        </span>
62+    </div>
63+   
64+
65 ``Paginator`` objects
66 =====================
67