Login

Pagination shortcut

Author:
piratus
Posted:
February 27, 2009
Language:
Python
Version:
1.0
Tags:
pagination
Score:
1 (after 1 ratings)

This is a function wrapping the code from example from django docs.

The required parameters are: request which is a Request object from a view, and objects - a list of objects to paginate.

You may want to tune number of items per page by specifying count and the name of a GET parameter through param_name

To use it in your view just wrap the paginated object into a function for example:

def someview(request):
    articles = Article.objects.all()
    ... some other logics ...
    return render_to_response(template, {'articles': paginate(request, articles)}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
def paginate(request, objects, count=10, param_name='page'):
    """
    Shortcut for paginating by some object
    """
    paginator = Paginator(objects, count)

    try:
        pagenum = int(request.GET.get('%s' % param_name, '1'))
    except ValueError:
        pagenum = 1
    
    try:
        result = paginator.page(pagenum)
    except (EmptyPage, InvalidPage):
        result = paginator.page(paginator.num_pages)
    
    return result

More like this

  1. object-oriented generic views by carljm 6 years, 10 months ago
  2. Simple Paginate by laserlight 2 years ago
  3. Django JSONP Decorator by cominatchu 4 years, 9 months ago
  4. Paginator TemplateTag by trbs 7 years, 3 months ago
  5. Decorator to limit request rates to individual views by jensbreit 6 years, 9 months ago

Comments

Please login first before commenting.