直接看代码吧,还算比较简单:
- 先确认数据量有多少
- 根据页面显示数据的多少来分割数据,得到页面的开始数据和结束数据
- 根据开始和截止数据去切片数据,并且得到总共的页码数
- 根据一页显示多少页码和当前页码数,得到开始和截止的页码
- 配置首页码、上一页、页码内容、下一页、末页
- 内容为字符串拼凑的HTML标签,并拼接到一起
- 导入mark_safe模块,将字符串转化为页码对象
HTML页面内容:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>page_test</title>
<style>
.selected{
background-color: lightblue;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<th>id</th>
<th>名称</th>
</tr>
</thead>
<tbody>
{% for item in data %}
<tr>
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<div>
{{ str_page }}
</div>
</body>
</html>
views.py内容:
def page(request):
# for i in range(200):
# name = 'cc'+str(i)
# models.Girl.objects.create(name=name)
current_page = request.GET.get('p', 1)
current_page = int(current_page)
start = (current_page - 1) * 10
end = current_page * 10
data = models.Girl.objects.all()[start:end]
total_item = models.Girl.objects.all().count()
a, b = divmod(total_item, 10)
if b == 0:
pass
else:
a += 1
str_page = CustomPage('?p=',current_page,a)
return render(request, 'page.html', {'data': data, 'str_page': str_page})
def CustomPage(baseurl,current_page,total_page):
#每页显示11页码
#perPage = 11
begin = 0
end = 0
if total_page <= 11:
begin = 0
end = total_page
else:
if current_page > 5:
begin = current_page - 5
end = current_page + 5
if end > total_page:
end = total_page
else:
begin = 0
end = 11
page_list = []
#编辑首页项
if current_page <= 1:
first = "<a href='#'>首页</a>"
else:
first = "<a href='%s%d'>首页</a>"%(baseurl,1)
page_list.append(first)
#编辑上一页选项
if current_page <= 1:
prev = "<a href='#'>上一页</a>"
else:
prev = "<a href='%s%d'>上一页</a>"%(baseurl,current_page-1)
page_list.append(prev)
#编辑中间页面项
for i in range(begin+1,end+1):
if i == current_page:
temp = "<a href='%s%d' class='selected'>%d</a>"%(baseurl,i,i)
else:
temp = "<a href='%s%d'>%d</a>"%(baseurl,i,i)
page_list.append(temp)
#编辑下一页选项
if current_page >= total_page:
nex = "<a href='#'>下一页</a>"
else:
nex = "<a href='%s%d'>下一页</a>"%(baseurl,current_page+1)
page_list.append(nex)
#编辑末页选项
if current_page >= total_page:
last = "<a href='#'>末页</a>"
else:
last = "<a href='%s%d'>末页</a>"%(baseurl,total_page)
page_list.append(last)
#拼接字符串
result = ' '.join(page_list)
#转换为HTML
from django.utils.safestring import mark_safe
return mark_safe(result)