标签:
分页是网站中比较常见的应用,django提供了一些类帮助管理分页的数据,这些类都位于django.core.paginator.py文件里面
class Paginator(object_list, per_page, orphans=0, allow_empty_first_page=True)
必需参数:
object_list:具有count()或者__len__()方法的可切片的对象,比如列表,元组或者django queryset
per_page:每页最大的条目数量
可选参数:
有三个异常,InvalidPage,PageNotAnInteger和EmptyPage,看下面的代码即可以知道他们之间的关系
class InvalidPage(Exception): pass class PageNotAnInteger(InvalidPage): pass class EmptyPage(InvalidPage): pass
Paginator.page()函数返回一个页对象,类原型是class Page(object_list,number,paginator)
最后我们看一下应用的例子吧:
视图函数:
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger def listing(request): contact_list = Contacts.objects.all() paginator = Paginator(contact_list, 25) # Show 25 contacts per page page = request.GET.get(‘page‘) try: contacts = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. contacts = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. contacts = paginator.page(paginator.num_pages) return render_to_response(‘list.html‘, {"contacts": contacts})
模板
{% for contact in contacts %} {# Each "contact" is a Contact model object. #} {{ contact.full_name|upper }}<br /> ... {% endfor %} <div class="pagination"> <span class="step-links"> {% if contacts.has_previous %} <a href="?page={{ contacts.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ contacts.number }} of {{ contacts.paginator.num_pages }}. </span> {% if contacts.has_next %} <a href="?page={{ contacts.next_page_number }}">next</a> {% endif %} </span> </div>
标签:
原文地址:http://www.cnblogs.com/qwj-sysu/p/4219775.html