Using ObjectPaginator in Your Own View

October 8, 2005

This wasn’t obvious to me and there is likely an easier way to get this done but… you can add the paging of the admin screens to your main templates by utilizing the ObjectPaginator. The generic view provide this free of charge w/out having to do anything, but your own pages don’t (AFAIK).

from django.core.paginator import ObjectPaginator, InvalidPage

Then get the paginator object:

paginator = ObjectPaginator(products, {’offset’:12} , paginate_by)

sending it the object, an offset and the number to page by. Next, you want to get the current page (if there is one):

page = int(request.GET.get(’page’, 0))

paginator will expose a number of function to control paging. You will then want to pass these on to your template.

def index(request):
paginate_by = 20
paginator = ObjectPaginator(products, {’offset’:2} , paginate_by)
page = int(request.GET.get(’page’, 0))
prods = paginator.get_page(page)
t = template_loader.get_template(’products/products_list’)
c = Context(request, {
‘prods’: prods,
‘is_paginated’ : True,
‘results_per_page’ : paginate_by,
‘has_next’: paginator.has_next_page(page),
‘has_previous’: paginator.has_previous_page(page),
‘page’: page + 1,
‘next’: page + 1,
‘previous’: page - 1,
‘pages’: paginator.pages
})
return HttpResponse(t.render(c))

Now in your template you can do something like this:

{% if has_previous %} <a href="?page={{ previous }}"> < < previous {{ page }} {% if has_next %} <a href=”?page={{ next }}”> next >> {% endif %}

Comments »

The URI to TrackBack this entry is: http://pythonanddjango.blogsome.com/2005/10/08/using-objectpaginator-in-your-own-view/trackback/

No comments yet.

RSS feed for comments on this post.

Leave a comment

Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>


Get free blog up and running in minutes with Blogsome | Theme designs available here