逻辑处理
class PageControl(object):
#参数分别代表当前页数、每一页的页数、总的页数、当前页面的路径
def __init__(self,current_page,per_page,all_count,url):
self.current_page = int(current_page)
self.per_page = per_page
self.all_count = all_count
a,b = divmod(all_count,per_page)
if b:
a+=1
self.all_page = a
self.url = url
def start(self):
return (self.current_page-1)*self.per_page
def end(self):
return self.current_page*self.per_page
def page_list(self):
s=[]
begin=self.current_page-3
final=self.current_page+4
if self.all_page<7:
for i in range(1, self.all_page+1):
if i == self.current_page:
v = "<li class='active'><a href='%s?page=%s'>%s</a></li>" % (self.url,i, i)
else:
v = "<li><a href='%s?page=%s'>%s</a></li>" % (self.url,i, i)
s.append(v)
if self.current_page<5:
for i in range(1, 8):
if i == self.current_page:
v = "<li class='active'><a href='%s?page=%s'>%s</a></li>" % (self.url,i, i)
else:
v = "<li><a href='%s?page=%s'>%s</a></li>" % (self.url,i, i)
s.append(v)
elif final>=self.all_page:
for i in range(self.all_page-6, self.all_page+1):
if i == self.current_page:
v = "<li class='active'><a href='%s?page=%s'>%s</a></li>" % (self.url,i, i)
else:
v = "<li><a href='%s?page=%s'>%s</a></li>" % (self.url,i, i)
s.append(v)
else:
for i in range(begin,final):
if i == self.current_page:
v = "<li class='active'><a href='%s?page=%s'>%s</a></li>" % (self.url,i, i)
else:
v = "<li><a href='%s?page=%s'>%s</a></li>" % (self.url,i, i)
s.append(v)
return ''.join(s)
def page_befor(self):
if self.current_page <= 1:
v = "<a href='#' aria-label='Previous'><span aria-hidden='true'>上一页</span></a>"
else:
v = "<a href='%s?page=%s' aria-label='Previous'><span aria-hidden='true'>上一页</span></a>"%(self.url, self.current_page-1)
return v
def page_next(self):
if self.current_page >= self.all_page:
v = "<a href='#' aria-label='Next'><span aria-hidden='true'>下一页</span></a>"
else:
v = "<a href='%s?page=%s' aria-label='Next'><span aria-hidden='true'>下一页</span></a>"%(self.url, self.current_page+1)
return v
调用上述模块
def custom(request):
page = request.GET.get("page")
pc = PageControl(page,10,models.UserInfo.objects.all().count(),'/app01/custom.html')
user_list = models.UserInfo.objects.all()[pc.start():pc.end()]
return render(request,'custom.html',{'user_list':user_list,'pc':pc})
前端页面展示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
#引入Bootstrap模板
<link rel="stylesheet" href="/static/plugins/bootstrap-3.4.1-dist/css/bootstrap.css">
</head>
<body>
<table class="table table-striped">
{% for user in user_list %}
<tr>
<td>{{ user.nid }}</td>
<td>{{ user.user }}</td>
<td>{{ user.age }}</td>
<td>{{ user.password }}</td>
<td>{{ user.ug.title }}</td>
</tr>
{% endfor %}
</table>
#调用Bootstrap模板渲染
<nav aria-label="Page navigation">
<ul class="pagination">
<li>
{{ pc.page_befor|safe }}
</li>
{{ pc.page_list|safe }}
<li>
{{ pc.page_next|safe }}
</li>
</ul>
</nav>
</body>
</html>