Django的分页器(paginator)
view.py
from django.shortcuts import render,HttpResponse
from app01.models import *
from django.core.paginator import Paginator,EmptyPage # 导入分页器Paginator和空白页组件EmptyPage
# Create your views here.
def index(request):
book_list=Book.objects.all() # 获取全部models对象
paginator=Paginator(book_list,5) # 将models对象传给分页器,设置每页有五个对象
# print('count:',paginator.count) # paginator.count为book_list的全部对象个数
# print('num_pages:',paginator.num_pages) # paginator.num_pages为一共有多少页(paginator.count/5)
# print('page_range:',paginator.page_range) # page_range, 一个页码range对象,比如38页: range(1,39)
try:
current_page_num=int(request.GET.get('page',1)) # page为url中问号后的参数页码的值, 如果没有值默认为1
# http://127.0.0.1:8000/index/?page=2
current_page=paginator.page(current_page_num) # 获取当前页码的所有对象
except EmptyPage as e: # 如果超出page传的参数超过页码范围会出现EmptyPage异常
current_page = paginator.page(1) # 这里给出默认值1
if paginator.num_pages > 11: # 这里的if判断是需要前端显示11个页码, 并对三种情况分别判断
if current_page_num - 5 < 1:
page_range = range(1, 12)
elif current_page_num + 5 > paginator.num_pages:
page_range= range(paginator.num_pages-11,paginator.num_pages+1)
else:
page_range = range(current_page_num-5,current_page_num+6)
else:
page_range=paginator.page_range
return render(request,'index.html',locals())
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title</title>
<link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<ul> // 显示对应页码的数据
{% for book in current_page %}
<li>{{ book.title }}</li>
{% endfor %}
</ul>
<nav aria-label="Page navigation"> // 分页器前端显示效果
<ul class="pagination">
{% if current_page.has_previous %}
<li><a href="?page={{ current_page_num|add:-1 }}" aria-label="Previous"><span
aria-hidden="true">«</span></a></li>
{% else %}
<li class="disabled"><a href="?page=1" aria-label="Previous"><span aria-hidden="true">«</span></a>
</li>
{% endif %}
{# <li><a href="?page={{ current_page_num|add:-1 }}" aria-label="Previous"><span aria-hidden="true">«</span></a></li>#}
{% for i in page_range %}
{% if current_page_num == i %}
<li class="active"><a href="?page={{ i }}">{{ i }}</a></li>
{% else %}
<li><a href="?page={{ i }}">{{ i }}</a></li>
{% endif %}
{% endfor %}
{% if current_page.has_next %}
<li><a href="?page={{ current_page_num|add:1 }}" aria-label="Next"><span aria-hidden="true">»</span></a></li>
{% else %}
<li class="disabled"><a href="" aria-label="Next"><span aria-hidden="true">»</span></a></li>
{% endif %}
</ul>
</nav>
</body>
</html>