共计 2502 个字符,预计需要花费 7 分钟才能阅读完成。
成果展现,依据以后页码显示前后各 5 页,有首页和尾页,上一页和下一页
pytho 代码
新建 py 文件:pageination.py
"""自定义分页组件"""
from django.utils.safestring import mark_safe
class Pageination(object):
"""
:param request: 申请的对象
:param queryset: 符合条件的数据(依据这个数据给他进行分页解决):param page_size: 每页显示多少条数据
:param page_param: 在 URL 中传递的获取分页的参数,例如:/etty/list/?page=12
:param plus: 显示当前页的 前或后几页(页码)"""def __init__(self, request, queryset, page_size=10, page_param='page', plus=5):
page = request.GET.get('page', 1)
# 判断是否为字符串十足
if page.isdecimal():
page = int(page)
else:
page = 1
# 获取当前页
self.page = page
# 每页显示条数
self.page_size = page_size
# 起始页
self.start = (page - 1) * page_size
# 完结页
self.end = page * page_size
self.page_queryset = queryset[self.start:self.end]
# 总条数
total_count = queryset.count()
total_page_count, div = divmod(total_count, page_size) # 获取整除数 与 余数
if div:
total_page_count += 1
# 总页码
self.total_page_count = total_page_count
# 显示页码数
self.plus = plus
def html(self):
# 计算出当前页前 5 页,和后 5 页
if self.total_page_count <= 2 * self.plus + 1:
start_page = 1
end_page = self.total_page_count
else:
# 数据地面的数据表较多 >11
if self.page <= self.plus:
start_page = 1
end_page = 2 * self.plus + 1
else:
if (self.page + self.plus) > self.total_page_count:
start_page = self.total_page_count - 2 * self.plus
end_page = self.total_page_count
else:
start_page = self.page - self.plus
end_page = self.page + self.plus + 1
# 生成页码
page_str_list = []
# 首页
page_str_list.append('<li><a href="?page=1"> 首页 </a></li>')
# 上一页
if self.page > 1:
prev = f'<li><a href="?page={self.page - 1}"> 上一页 </a></li>'
else:
prev = f'<li><a href="?page={1}"> 上一页 </a></li>'
page_str_list.append(prev)
for i in range(start_page, end_page + 1):
if i == self.page:
ele = f'<li class="active"><a href="?page={i}">{i}</a></li>'
else:
ele = f'<li><a href="?page={i}">{i}</a></li>'
page_str_list.append(ele)
# 下一页
if self.page < self.total_page_count:
prev = f'<li><a href="?page={self.page + 1}"> 下一页 </a></li>'
else:
prev = f'<li><a href="?page={self.total_page_count}"> 下一页 </a></li>'
page_str_list.append(prev)
# 尾页
page_str_list.append(f'<li><a href="?page={self.total_page_count}"> 尾页 </a></li>')
# 输出页码跳转
search_string = """<form method="get">
<div class="input-group">
<input type="text" name="page" class="form-control" placeholder="Search for...">
<span class="input-group-btn">
<button class="btn btn-default" type="submit"> 跳转 </button>
</span>
</div>
</form>
"""
page_str_list.append(search_string)
# 转换为 HTML 元素
page_string = mark_safe(''.join(page_str_list))
return page_string
调用页码:
page_object = Pageination(request, queryset)
context = {
'queryset': page_object.page_queryset,
'search_data': search_data, # 分完页的数据
'page_string': page_object.html(), # 页码}
return render(request, 'pretty_list.html', context)
html 中应用
<nav aria-label="Page navigation">
<ul class="pagination">
{{page_string}}
</ul>
</nav>
正文完