Ticket #9215: pagination.diff

File pagination.diff, 2.2 KB (added by Scot Hacker, 16 years ago)

Formatting corrections to original patch

  • docs/topics/pagination.txt

     
    7575    objects such as Django's ``QuerySet`` to use a more efficient ``count()``
    7676    method when available.
    7777
     78
     79Implementation Example
     80======================
     81
     82A working example of a view and accompanying template might look like this,
     83assuming you want to display a multi-page listing of an existing "Contacts"
     84model:
     85
     86In :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
     112In template :file:`list.html`, you'll want navigation between pages.
     113Note that you can simply output the page object as ``{{ contacts }}`` to
     114render 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
    78134``Paginator`` objects
    79135=====================
    80136
Back to Top