Login

Pagination shortcut

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

Comments

Please login first before commenting.