New Django Paginator Example

4 Aug
2008
edit:
This example has since been added to the official Django Docs for pagination. Big thanks to Scot Hacker for taking the initiative to submit the doc patch and make this happen (IE I’m far to lazy to submit it on my own).

So 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:

 Python |  copy code |? 
01
from django.core.paginator import Paginator
02
 
03
#create a new paginator instance by passing it a collection of objects and the per page count
04
paginator = Paginator(Contact.objects.all().order_by('last_name'), 10)
05
 
06
#get the page number from a get param
07
#if param is blank then set page to 1
08
page = int(request.GET.get('page', '1'))
09
 
10
#grab the current page from the paginator...
11
contacts = paginator.page(page)
12
 
13
#render the template and pass the contacts page into the template
14
return render_to_response('contacts.html',{'contacts':contacts})


in your template:
 Python |  copy code |? 
1
{% for contact in contacts.object_list %}
2
{{ contact.name }}
3
{% 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.
Bookmark and Share

2 Responses to New Django Paginator Example

Avatar

scot hacker’s foobar blog » Notes on a Django Migration

November 19th, 2008 at 12:46 pm

[...] applicable to common scenarios, which I can use a starting point. Fortunately, I found an excellent blog post on Django pagination in the wild. After corresponding with the author a bit, I was able to modify [...]

Avatar

Ninjacipher » Blog Archive » Django Pagination Wrapper

January 25th, 2009 at 1:28 pm

[...] of the features the wrapper provides are now part of the core pagination classes. Please see my newer post about the topic (with [...]

Comment Form

top