views中
思路:
views
1、将数据库内容按 10条/页 显示在前端
2、排错:EmptyPage 当page=-1时 显示首页
3、当数据量大时,分页器上限制限制页码数量
前端
1、遍历显示数据库传来的当前页信息
2、上一页,下一页的<a>链接
3、利用bootstrap,历遍显示页码,实现鼠标悬浮变色
views
# 分页器 from app01.models import Book from django.core.paginator import Paginator,EmptyPage def page(request): ''' book_list=[] 数据批量插入一张数据表中 for i in range(0,101): book_obj = Book(name='book%s'%i,price=i*i) book_list.append(book_obj) Book.objects.bulk_create(book_list) ''' # 分页器的试用 booklist = Book.objects.all() paginator = Paginator(booklist,10) #每页最多显示10个数据 print(paginator.count) # 数据总数 print(paginator.num_pages) # 总页数 print(paginator.page_range) # 页码列表 current_page_num = int(request.GET.get('page', 1)) # 得到一个参数page默认等于1 前端?page=1 #分页器上最多显示11个页码 if paginator.num_pages>11: if current_page_num-5 <= 0: page_range = range(1, 11) 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 + 5) else: page_range = paginator.page_range try: #防止page=-1时报错 current_page = paginator.page(current_page_num) for i in current_page: #遍历当前页的数据 print(i) # page2 = paginator.page(2) # page2.has_next() 是否有下一行 # page2.next_page_number() 下一页页码 # page2.has_previous() 是否有上一页 # page2.previous_page_number() 上一页页码
except EmptyPage as e: current_page = paginator.page(1) #第一页的page对象 return render(request,'page.html',locals())
前端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
{#每页显示内容#}
<ul>
{% for book in current_page %}
<li>{{ book.name }}:{{ book.price }}</li>
{% endfor %}
</ul>
{#分页器#}
<nav aria-label="Page navigation">
<ul class="pagination">
{#判断首页与尾页 判断是否还有上一页#}
{% if current_page.has_previous %}
<li>
{#分页a标签跳转当前页面,直接“?+跳转页”#}
<a href="?page={{ current_page_num|add:-1 }}" 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 i in page_range %}
{% if current_page_num == i %}
{#鼠标选择时颜色变深 class=active既能渲染深色#}
<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.next_page_number }}" 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>