Login

Simple Paginate

Author:
laserlight
Posted:
June 18, 2013
Language:
Python
Version:
Not specified
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. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

Please login first before commenting.