Pagination in Django

By Joseph Jude on May 12, 2008
Posted Under: Programming
Print This Post Print This Post

Most often it is necessary to paginate the results. Django comes up with a simple but pretty neat pagination out-of-the-box. Paginating is easy and simple.

Import first:

from django.core.paginator import Paginator, InvalidPage 

Get the results. I read somewhere that Django delays execution of queries until necessary. If so, then this will not impact any performance.

info_list = Paginator(sol.objects.all(),paginate_by) 

Now build the dictionary values to be passed to the template.

try:
	page_info = info_list.page(page_num)
except InvalidPage:
	page_num = 1
	page_info = info_list.page(page_num)

has_previous = page_info.has_previous()
has_next = page_info.has_next()

info_dict = {
	'query_list' : page_info.object_list,
	'has_previous' : page_info.has_previous(),
	'previous_page' : page_info.previous_page_number(),
	'has_next' : page_info.has_next(),
	'next_page' : page_info.next_page_number(),
	'site_name' : 'sol',
	'user' : request.user,
}

That is it. Now this can be called as:

{% for item in query_list %}
<tr class="itemrow">
<td class="itemcol"><a href="{{ item.get_absolute_url }}"> {{item.title}}</a></td>
<td class="itemcol">
<ul>
{% for author in item.authors.all %}
    <li> <a href="{{author.get_absolute_url}}" title="{{author.name}}">{{author.name}}</a> </li>
{%endfor %}
</ul>
</td>
</tr>
{% endfor %}

This will enable pagination for the entries. Simple right?

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • StumbleUpon
  • Reddit
  • Bloglines
  • email
  • Facebook
  • LinkedIn
  • MySpace
  • Squidoo
  • Technorati
  • TwitThis
  • Google Bookmarks
Tags:

Reader Comments

#1 
Written By anonymous on May 14th, 2008 @ 3:25 am

Add a Comment

required, use real name
required, will not be published
optional, your blog address

Previose Post: First Experience