from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
def index(request):
current_page = request.GET.get('page')
user_list = UserInfo.objects.all()
paginator = Paginator(user_list, 10)
# per_page: 每页显示条目数量
# count: 数据总个数
# num_pages:总页数
# page_range:总页数的索引范围,如: (1,10),(1,200)
# page: page对象
try:
posts = paginator.page(current_page)
except PageNotAnInteger as e:
posts = paginator.page(1)
except EmptyPage as e:
posts = paginator.page(1)
# has_next 是否有下一页
# next_page_number 下一页页码
# has_previous 是否有上一页
# previous_page_number 上一页页码
# object_list 分页之后的数据列表
# number 当前页
# paginator paginator对象
return render(request, 'index.html', {'posts':posts})
html:
<ul>
{% for user in posts.object_list %}
<li>{{ user.name }}</li>
{% endfor %}
</ul>
<div>
{% if posts.has_previous %}
<a href="/index/?page={{ posts.previous_page_number }}">上一页</a>
{% endif %}
# 显示所有页码,
{% for num in posts.paginator.page_range %}
<a href="/index/?page={{ num }}">{{ num }}</a>
{% endfor %}
{% if posts.has_next %}
<a href="/index/?page={{ posts.next_page_number }}">下一页</a>
{% endif %}
</div>
1