Login

Simple Paginate

Author:
laserlight
Posted:
June 18, 2013
Language:
Python
Version:
Not specified
Tags:
pagination paginator paginate
Score:
0 (after 0 ratings)

This function wraps boilerplate code to get the current page in a view, obtaining the page number from some URL query string variable, e.g., ?page=2

The interface is inspired by the interface of Paginator. The implementation follows an example given in Django documentation.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger


def paginate(request,
             object_list,
             per_page,
             orphans=0,
             allow_empty_first_page=True,
             query_string_name="page"):
    """
    Returns a Page object using the page number from the URL query string.
    """
    paginator = Paginator(object_list,
                          per_page,
                          orphans=orphans,
                          allow_empty_first_page=allow_empty_first_page)

    page_number = request.GET.get(query_string_name, "1")
    try:
        page = paginator.page(page_number)
    except PageNotAnInteger:
        # Page number is not an integer: deliver the first page.
        page = paginator.page(1)
    except EmptyPage:
        # Page number is out of range: deliver the last page.
        page = paginator.page(paginator.num_pages)
    return page

More like this

  1. paginator using url tag by fivethreeo 7 years, 7 months ago
  2. Django Twitter Bootstrap 3 pagination by Ragnar_Lodbrok 1 year, 1 month ago
  3. Stateful paginator, digg style by miracle2k 7 years ago
  4. A tip for preserving GET arguments with pagination by achimnol 5 years, 9 months ago
  5. Simple Paginator Function by goodsanket 5 years, 2 months ago

Comments

Please login first before commenting.