HTML代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="/static/bootstrap-3.3.7/dist/css/bootstrap.css">
<link rel="stylesheet" href="/templates/bootstrap-3.3.7/dist/css/bootstrap-theme.css">
<script src="/static/jquery3.js"></script>
<script src="/static/bootstrap-3.3.7/dist/js/bootstrap.js"></script>
</head>
<body>
<h1>图书列表</h1>
<table border="1" class="table table-bordered table-hover">
<thead>
<tr>
<th>ID</th>
<th>名字</th>
<th>出版社</th>
<th>价格</th>
</tr>
</thead>
<tbody>
{% for book in book_list %}
<tr>
<td>{{ book.id }}</td>
<td>{{ book.title }}</td>
<td>
{{ book.publisher.name }}
</td>
<td>{{ book.price }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{#重点位置#}
<nav aria-label="Page navigation">
<ul class="pagination">
<li>
<a href="/ormtest/book/?page=1" aria-label="Previous">
<span aria-hidden="true">首页</span>
</a>
</li>
{{ page_html|safe }}
<li>
<a href="/ormtest/book/?page={{ total_page }}" aria-label="Next">
<span aria-hidden="true">尾页</span>
</a>
</li>
</ul>
</nav>
</body>
</html>
Python 代码
def book_list(request):
# 每一页显示数量
per_page = 7
# 总数据
total_count = models.Book.objects.all().count()
# 总共需要多少页显示数据
total_page, m = divmod(total_count, per_page)
if m:
total_page += 1
# 从URL中取参数,当没有page时,page_num为1,当page_num大于总页数时,赋于最后一页,当page为字符时,异常出错时,为1值
try:
page_num = request.GET.get("page")
page_num = int(page_num)
if page_num > total_page:
page_num = total_page
elif page_num < 1:
page_num =1
except Exception as e:
page_num = 1
#定义两个变量,截取数据
data_start = (page_num-1)*per_page
data_end = page_num*per_page
#页面上总共展示多少页面
max_page =11
if total_page < max_page:
max_page = total_page
half_max_page = max_page//2 #结果为5,即左右各5页
# 页面上展示的面码从那儿结束
page_end = page_num + half_max_page
#页面上展示的页码从那儿开始
page_start = page_num - half_max_page
#如果当前面减一半比1还小
if page_start <= 1:
page_start = 1
page_end = max_page
#如果当前页大于总页数
if page_end >= total_page:
page_end = total_page
page_start = total_page-max_page+1
#在后台拼接分页的html
html_str_list = []
for i in range(page_start, page_end+1):
#为当前加一个active样式
if i == page_num:
tmp = ‘<li class=active><a href="/ormtest/book/?page={0}">{0}</a></li>‘.format(i)
else:
tmp = ‘<li><a href="/ormtest/book/?page={0}">{0}</a></li>‘.format(i)
html_str_list.append(tmp)
#将所有li的html文件拼接连接成一块
page_html = "".join(html_str_list)
#print(page_html)
all_book = models.Book.objects.all()[data_start:data_end]
return render(request,"book.html",{"book_list":all_book,"page_html":page_html,"total_page":total_page})
展示效果
原文地址:https://blog.51cto.com/12965094/2395798
时间: 2024-11-24 17:02:18