文章目录
2018-12-27 10:48:10
分页
- 分页django自带模块Paginator, EmptyPage, PageNotAnInteger
#views.py
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
def login(request):
obj_li = models.UserInfo.objects.all()
p = Paginator(obj_li,4) #将数据库中所有数据按每页4个的方式显示
get_page = int(request.GET.get('page',1)) #获取GET的page关键字的value(页码)
# print(p.page_range)
# get_page = int(request.GET.get('page',1))
try:
obj_li = p.page(get_page) #obj_li此时已经重新赋值,有分页的方法
#print(obj_li)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
obj_li = p.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
obj_li = p.page(p.num_pages)
return render(request,'login.html', locals()) #obj_li,p,get_page传到前端
- 前端
#login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% for contact in obj_li %} #将数据显示出来
{{ contact.id}}
{{ contact.name}}
{{ contact.password}}
{{ contact.age}}
{{ contact.username}}
{% endfor %}
<hr>
<div class="pagination">
<span class="step-links">
{% if obj_li.has_previous %} #判断是否有上一页
<a href="?page={{ obj_li.previous_page_number }}">上一页</a>
{% endif %}
{% for num in p.page_range %} #所有页数标记显示出来,按照GET的页码
{% if num == get_page %}
<a href="?page={{ num }}">{{ num }}</a> #page为传到后台的关键字
{% else %}
<a href="?page={{ num }}">{{ num }}</a>
{% endif %}
{% endfor %}
{% if obj_li.has_next %}#判断是否有下一页
<a href="?page={{ obj_li.next_page_number }}">下一页</a>
{% endif %}
</span>
</div>
</body>
</html>