New Django Paginator Example
Monday, August 4th, 2008So I pulled the latest Django codebase from svn today and I noticed that my old pagination setup no longer works. Not really surprising as a ton of stuff is being updated due to the coming release of 1.0. So I did a bit of digging into the new pagination code to see if I could rework my wrapper class to work with the new release. It turns out that with the updates there really is no good reason to wrap the classes any more. They have done a good job of working out all the kinks in the pagination setup and it does everything I need it to do out of the box.
So here is a quick nutshell example of how I am using the new django.core.paginator classes to replace the old ObjectPaginator wrapper from my previous example.
in your view:
from django.core.paginator import Paginator
#create a new paginator instance by passing it a collection of objects and the per page count
paginator = Paginator(Contact.objects.all().order_by('last_name'), 10)
#get the page number from a get param
#if param is blank then set page to 1
page = int(request.GET.get('page', '1'))
#grab the current page from the paginator...
contacts = paginator.page(page)
#render the template and pass the contacts page into the template
return render_to_response('contacts.html',{'contacts':contacts})
in your template:
{% for contact in contacts.object_list %}
{{ contact.name }}
{% endfor %}
I’d say that’s pretty easy. Here is a link to a simple snippet that you can use to create a paging footer.
Notice to get the page of pages info all you have to do is output the page object like so… {{ contacts }} . Pretty cool.