如果页数太多的话,全部显示在页面上就会显得很冗杂
@H_419_10@
可以在页面中显示规定的页码数
例如:
book_List.HTML:
<!DOCTYPE HTML><HTML lang="en"><head> <Meta charset="UTF-8"> <Title>书籍列表</Title> <link rel="stylesheet" href="/static/bootstrap/CSS/bootstrap.min.CSS"></head><body><div > <table > <thead> <tr> <th>序号</th> <th>ID</th> <th>书名</th> </tr> </thead> <tbody> {% for book in books %} <tr> <td>{{ forloop.counter }}</td> <td>{{ book.ID }}</td> <td>{{ book.Title }}</td> </tr> {% endfor %} </tbody> </table> <nav aria-label="Page navigation"> <ul > <li> <a href="#" aria-label="PrevIoUs"> <span aria-hIDden="true">«</span> </a> </li> <li> {{ page_HTML|safe }} </li> <li> <a href="#" aria-label="Next"> <span aria-hIDden="true">»</span> </a> </li> </ul> </nav></div></body></HTML>
vIEws.py:
from django.shortcuts import renderfrom app01 import modelsdef book_List(request): # 从 URL 中取参数 page_num = request.GET.get("page") print(page_num,type(page_num)) page_num = int(page_num) # 定义两个变量保存数据从哪儿取到哪儿 data_start = (page_num-1)*10 data_end = page_num*10 # 书籍总数 total_count = models.Book.objects.all().count() # 每一页显示多少条数据 per_page = 10 # 总共需要多少页码来显示 total_page,m = divmod(total_count,per_page) # 页面上最多展示的页码 max_page = 11 half_max_page = max_page // 2 # 页面上展示的页码的开始页 page_start = page_num - half_max_page # 页面上展示的页码的结束页 page_end = 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 # 如果还有数据 if m: total_page += 1 all_book = models.Book.objects.all()[data_start:data_end] # 拼接 HTML 的分页代码 HTML_List = [] for i in range(page_start,page_end+1): tmp = ‘<li><a href="/book_List/?page={0}">{0}</a></li>‘.format(i) HTML_List.append(tmp) page_HTML = "".join(HTML_List) return render(request,"book_List.HTML",{"books": all_book,"page_HTML": page_HTML})
运行结果:
总结以上是内存溢出为你收集整理的Python - Django - 页面上展示固定的页码数全部内容,希望文章能够帮你解决Python - Django - 页面上展示固定的页码数所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)