django之分页查询

1.自定义分页函数

#第一个参数:request对象;第二个参数:需要分页的数据;第三个参数:每页显示的数据个数;第四个参数:需要返回的网页---->"myadmin/user/index.html"

#导入分页类

from django.core.paginator import Paginator

def page(r,data,pagenum,path):
# 实例化分页类
paginator = Paginator(data,pagenum)
# 获取当前页码
p = int(r.GET.get('p',1))
# 获取当前页码的数据
pagedata = paginator.page(p)
# 获取总页码数
pagecount = paginator.num_pages
# 获取页码范围,循环
pagerange = paginator.page_range
# 对页码进行判断,防止页码小于1或大于最大页码数
if p < 1:
p = 1
if p > pagecount:
p = pagecount
# 返回页码循环数,在模板里遍历
if p <= 5:
page_list = pagerange[:10]
elif p + 5 > pagecount:
page_list = pagerange[-10:]
else:
page_list = pagerange[p-5:p+4]
# 返回分页后的数据,分页范围循环,当前页码
return render(r,path,{'info':pagedata,'page_list':page_list,'p':p})
2.视图函数中 调用函数,传递实参

   return page(request,data,20,'myadmin/user/userlist.html')

 3.模板中遍历数据

<div class="am-u-sm-12">
<table width="100%" class="am-table am-table-compact am-table-striped tpl-table-black " id="example-r">
<thead>
<tr>
<th>id</th>
<th>头像</th>
<th>用户名</th>
<th>密码</th>
<th>手机号码</th>
<th>年龄</th>
<th>性别</th>
<th>状态</th>
<th>邮箱</th>
<th>添加时间</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for i in info %}
<tr class="gradeX">
<td>{{ i.id }}</td>
<td><img src="{{ i.pic_url }}" alt="" width="50"></td>
<td>{{ i.username }}</td>
<td>******</td>
<td>{{ i.phone }}</td>
<td>{{ i.age }}</td>
<td>
{% if i.sex == '0' %}女
{% else %}男
{% endif %}
</td>
<td>
{% if i.status == 0 %}正常
{% else %}异常
{% endif %}
</td>
<td>{{ i.email }}</td>
<td>{{ i.addtime }}</td>
<td>
<div class="tpl-table-black-operation">
<a href="{% url 'admin_useredit' i.id %}">
<i class="am-icon-pencil"></i> 编辑
</a>
<a href="{% url 'admin_userdel' i.id %}" class="tpl-table-black-operation-del">
<i class="am-icon-trash"></i> 删除
</a>
</div>
</td>
</tr>
{% endfor %}
<!-- more data -->
</tbody>
</table>
</div>
<div class="am-u-lg-12 am-cf">
<div class="am-fr">
<ul class="am-pagination tpl-pagination">
<li>
<a href="?p={{p|add:-1}}">«</a>
</li>
{% for i in page_list %}
<li {% if p == i %} class="am-active" {% endif %}>
<a href="?p={{i}}&types={{ request.GET.types }}&keywords={{ request.GET.keywords }}">{{i}}</a>

</li>
{% endfor %}
<li>
<a href="?p={{p|add:1}}">»</a>
</li>
</ul>
</div>
</div>
 

猜你喜欢

转载自www.cnblogs.com/cage0515/p/9991170.html