分页功能是django的一个模块,可以直接导入:
from django.core.paginator import Paginator
主要的方法函数是page,可以通过实例化的paginator.page(i)指定返回第i页的page对象,但是如果i指定的内容是错的,就会产生一个错误。
除此之外,Paginator还有no_pages,page_range属性,分别表示全部页数和产生页码迭代器.
page()方法函数所返回的Page对象具有以下常见的方法函数:
has_next()
has_previous()
has_other_pages()
next_page_number()
previous_page_number()
下面是一个例子:
views.py:
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
def index(request):
all_polls = models.Poll.objects.all().order_by('-created_at')
paginator = Paginator(all_polls,5)
p = request.GET.get('p')
try:
polls = paginator.page(p)
except PageNotAnInteger:
polls = paginator.page(1)
except EmptyPage:
polls = paginator.page(paginator.num_pages)
template = get_template('index.html')
request_context = RequestContext(request)
request_context.push(locals())
html = template.render(request_context)
return HttpResponse(html)
index.html
<div class="row">
<button class='btn btn-info'>
目前是第{{ polls.number }}页
</button>
{% if polls.has_previous %}
<button class="btn-info btn">
<a href="?p={{ polls.prvious_page_number }}">上一页</a>
</button>
{% endif %}
{% if polls.has_next %}
<button class="btn-info btn ">
<a href="?p={{ polls.next_page_number }}">下一页</a>
</button>
{% endif %}
</div>