Django 系列博客(十五)
Django 系列博客(十五)
前言
本篇博客介绍使用 Django 的分页器组件完成分页功能。
分页器简介
在页面数据量过多时,一次性显示所有页面会造成页面不美观,这时候需要分页,不一次性显示所有页面,随当前页的变化而动态改变分页区间。
分页器组件常用方法
from django.core.paginator import Paginator
Paginator对象:paginator = Paginator(object_list, 10) # 10为每页为十条数据
paginator.per_page: 每页显示条数 # 为10
paginator.count: 数据总数
paginator.num_pages: 总页数
paginator.page_range: 总页数的索引范围,如:(1, 10), (1, 100)
page对象:page = paginator.page(current_page)
page.has_next: 是否有下一页
page.next_page_number: 下一页页码
page.has_previous: 是否有上一页
page.object_list: 分页之后的数据列表
page.paginator: paginator 对象
view 层
批量插入数据
def pagetest(request):
# 批量插入数据
li = []
for i in range(100):
li.append(UserInfo.objects.create(name='musibii%s' %i, pwd='woloveyou%s' %i))
ret = UserInfo.objects.bulk_create(li, 20)
return HttpResponse('ok')
逻辑代码
def pagelist(request):
user = UserInfo.objects.all().order_by('pk')
paginator = Paginator(user, 3)
try:
currentpage = int(request.GET.get('page', 1))
# page = paginator.page(currentpage)
print(currentpage)
except:
currentpage = 1
page = paginator.page(currentpage)
if paginator.num_pages > 11:
if currentpage - 5 <= 1 :
page_range = range(1, 12)
elif currentpage + 5 >= paginator.num_pages:
page_range = range(paginator.num_pages-10, paginator.num_pages+1)
else:
page_range = range(currentpage - 5, currentpage + 6)
else:
page_range = paginator.page_range
return render(request, 'pagelist.html', locals())
模板层
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>pagelist</title>
<link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css">
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-md-offset-3 col-md-6">
<table class="table">
<thead>
<tr>
<th>编号</th>
<th>姓名</th>
<th>密码</th>
</tr>
</thead>
<tbody>
{% for user in page %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ user.name }}</td>
<td>{{ user.pwd }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<nav aria-label="Page navigation">
<ul class="pagination">
{% if page.has_previous %}
<li>
<a href="/pagelist/?page={{ page.previous_page_number }}" aria-label="Previous">
<span aria-hidden="true">上一页</span>
</a>
</li>
{% else %}
<li class="disabled">
<a href="#" aria-label="Previous">
<span aria-hidden="true">上一页</span>
</a>
</li>
{% endif %}
{% for foo in page_range %}
{% if currentpage == foo %}
<li class="active"><a href="/pagelist/?page={{ foo }}">{{ foo }}</a></li>
{% else %}
<li><a href="/pagelist/?page={{ foo }}">{{ foo }}</a></li>
{% endif %}
{% endfor %}
{% if page.has_next %}
<li>
<a href="/pagelist/?page={{ page.next_page_number }}" aria-label="Previous">
<span aria-hidden="true">下一页</span>
</a>
</li>
{% else %}
<li class="disabled">
<a href="#" aria-label="Previous">
<span aria-hidden="true">下一页</span>
</a>
</li>
{% endif %}
</ul>
</nav>
</div>
</div>
</div>
</body>
</html>