Pagination

When you have a lot of data to sift through pagination is one of the best ways we have to visually breakup data so it is not as daunting. In this video we will use the Paginator built right into Django. It is much simpler than it sounds like it might be.
home/views.py
from django.core.paginator import Paginator

def index(request):
    posts_list = Post.objects.all().order_by('-id')

    paginator = Paginator(posts_list, 5)

    try:
        page = int(request.GET.get('page', '1'))
    except:
        page = 1

    try:
        posts = paginator.page(page)
    except(EmptyPage, InvalidPage):
        posts = paginator.page(paginator.num_pages)

    return render_to_response('home/index.html',
        { 'posts' : posts },
        context_instance=RequestContext(request))
template/home/index.html
{% if posts %}
    {% for post in posts.object_list %}
        <a href="{% url post.views.post post.id post.slug %}">{{ post.title }}</a>
        {{ post.body|truncatewords:80 }}
    {% endfor %}
    <div class="pagination">
      <ul>
          {% if posts.has_previous %}
              <li><a href="?page={{ posts.previous_page_number }}">Previous</a></li>
          {% endif %}
          {% for pg in posts.paginator.page_range %}
              {% if posts.number == pg %}
                  <li class="active"><a href="?page={{ pg }}">{{ pg }}</a></li>
              {% else %}
                  <li><a href="?page={{ pg }}">{{ pg }}</a></li>
              {% endif %}
          {% endfor %}
          {% if posts.has_next %}
              <li><a href="?page={{ posts.next_page_number }}">Next</a></li>
          {% endif %}
      </ul>
    </div>
{% endif %}
comments powered by Disqus