| 78 | |
| 79 | Implementation Example |
| 80 | ====================== |
| 81 | |
| 82 | A working example of a view and accompanying template might look like this, |
| 83 | assuming you want to display a multi-page listing of an existing "Contacts" |
| 84 | model: |
| 85 | |
| 86 | In :file:`views.py`: :: |
| 87 | |
| 88 | from django.core.paginator import Paginator, InvalidPage, EmptyPage |
| 89 | |
| 90 | def listing(request): |
| 91 | contact_list = Contacts.objects.all() |
| 92 | paginator = Paginator(contact_list, 25) # Show 25 contacts per page |
| 93 | |
| 94 | # Make sure page request is an int. If not, deliver first page. |
| 95 | try: |
| 96 | page = int(request.GET.get('page', '1')) |
| 97 | except ValueError: |
| 98 | page = 1 |
| 99 | |
| 100 | # If page request (9999) is out of range, deliver last page of results. |
| 101 | try: |
| 102 | contacts = paginator.page(page) |
| 103 | except (EmptyPage, InvalidPage): |
| 104 | contacts = paginator.page(paginator.num_pages) |
| 105 | |
| 106 | return render_to_response( |
| 107 | 'list.html', |
| 108 | locals(), |
| 109 | context_instance=RequestContext(request) |
| 110 | ) |
| 111 | |
| 112 | In template :file:`list.html`, you'll want navigation between pages. |
| 113 | Note that you can simply output the page object as ``{{ contacts }}`` to |
| 114 | render the "page *n* of pages" information.:: |
| 115 | |
| 116 | {% for contact in contacts.object_list %} |
| 117 | {{ contact.full_name|upper }}<br /> |
| 118 | ... |
| 119 | {% endfor %} |
| 120 | |
| 121 | <div class="pagination"> |
| 122 | <span class="step-links"> |
| 123 | {% if contacts.has_previous %}<a href="?page={{ contacts.previous_page_number }}" |
| 124 | class="util-link">previous</a>{% endif %} |
| 125 | <span class="current"> |
| 126 | {{ contacts }} |
| 127 | </span> |
| 128 | {% if contacts.has_next %}<a href="?page={{ contacts.next_page_number }}" |
| 129 | class="util-link">next</a>{% endif %} |
| 130 | </span> |
| 131 | </div> |
| 132 | |
| 133 | |