- 导入django内置的分页器
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
- 定义一个分页器函数
def make_paginator(objects, page, num=1):
paginator = Paginator(objects, num)
try:
object_list = paginator.page(page)
except PageNotAnInteger:
object_list = paginator.page(1)
except EmptyPage:
object_list = paginator.page(paginator.num_pages)
return object_list, paginator
- 在index中将文章总数和当前访问页码传入分页器函数
def index(request):
entries = models.Entry.objects.all()
page = request.GET.get('page', 1)
entry_list, paginator = make_paginator(entries, page)
page_data = pagination_data(paginator, page)
return render(request, 'blog/index.html', locals())
{% if entry_list.has_previous %}
<li><a href="?page={{ entry_list.previous_page_number }}"><i class="glyphicon glyphicon-chevron-left"></i>前一页</a></li>
{% endif %}
{% if first %}
<li><a href="?page=1">1</a></li>
{% endif %}
{% if left %}
{% if left_has_more %}
<span>...</span>
{% endif %}
{% for i in left %}
<li><a href="?page={{ i }}">{{ i }}</a></li>
{% endfor %}
{% endif %}
<li class="active"><a href="?page={{ entry_list.number }}">{{ entry_list.number }}</a></li>
{% if right %}
{% for i in right %}
<li><a href="?page={{ i }}">{{ i }}</a></li>
{% endfor %}
{% if right_has_more %}
<span>...</span>
{% endif %}
{% endif %}
{% if last %}
<li><a href="?page={{ entry_list.num_pages }}">{{ entry_list.num_pages }}</a></li>
{% endif %}
{% if entry_list.has_next %}
<li><a href="?page={{ entry_list.next_page_number }}">下一页<i class="glyphicon glyphicon-chevron-right"></i></a></li>
{% endif %}
</ul>