按照之前的笔记添加一个嘉宾管理,在此不重复说明。
在django中使用paginator类来实现分类功能。修改../sign/views.py文件
#导入类
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
def guest_search_name(request):
username = request.session.get('user', '')
guest_search_name = request.GET.get("realname", "")
guest_list = Guest.objects.filter(realname__contains=guest_search_name)
paginator = Paginator(guest_list, 2) #创建每页2条数据的分页器
page = request.GET.get('page') #通过get请求得到当前要显示的第几页数据
try:
contacts = paginator.page(page) #获取第page页的数据,如果没有抛出异常
except PageNotAnInteger:
# 如果page页不是整数,取第1页数据
contacts = paginator.page(1)
except EmptyPage:
# 如果page不在范围,取最后1页数据
contacts = paginator.page(paginator.num_pages)
return render(request, "guest_manage.html", {"user": username, "guests": contacts})
在guest_manage.html中添加列表分页器:
<!-- 列表分页器 -->
<div class="pagination">
<span class="step-links">
{% if guests.has_previous %}
<a href="?page={{ guests.previous_page_number }}">上一页</a>
{% endif %}
<span class="current">
第 {{ guests.number }} 页,共 {{ guests.paginator.num_pages }} 页
</span>
{% if guests.has_next %}
{% if phone %}
<a href="?page={{ guests.next_page_number }}">下一页</a>
{% else %}
<a href="?page={{ guests.next_page_number }}">下一页</a>
{% endif %}
{% endif %}
</span>
</div>
效果如下: