(编辑:jimmy 日期: 2024/11/16 浏览:2)
本文实例讲述了Django框架实现的分页。分享给大家供大家参考,具体如下:
首先初始化model,建表
class Book(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Meta: db_table = 'books'
然后用pycharm的数据库模块可视化插入
分页思路
url传递参数http://127.0.0.1:8000/books/"htmlcode">
def books(request): #取从url传递的参数 page_num = request.GET.get('page') page_num = int(page_num) start = (page_num-1)*5 end = page_num*5 #总页码数是"/books/" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >{}</li>'.format(i,i) html_str_list.append(tmp) page_html = "".join(html_str_list) return render(request,'books.html',{'books':all_books,'total_page':total,'page_html':page_html})
拿到数据总量的值,每一页的数量为5,如果有余数则total+1也就是增加一个页面.
建立一个列表,去拼接a标签,最后传递给前端
前端
前端的样式用到了boottrap,可以直接看文档.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>书记列表</title> <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.css" rel="external nofollow" > </head> <body> <div class="container"> <table class="table table-bordered"> <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.name }}</td> </tr> {% endfor %} </tbody> </table> <nav aria-label="Page navigation"> <ul class="pagination"> <li> <a href="#" rel="external nofollow" rel="external nofollow" aria-label="Previous"> <span aria-hidden="true">«</span> </a> </li> {{ page_html|safe }} <li> <a href="#" rel="external nofollow" rel="external nofollow" aria-label="Next"> <span aria-hidden="true">»</span> </a> </li> </ul> </nav> </div> </body> </html>
{{ page_html|safe }}
传递过来的page_html要用safe过滤器,不然无法转移成html.
最终效果
分页优化
设置一个首页一个尾页,以及显示局部的页面
def books(request): # 取从url传递的参数 page_num = request.GET.get('page') page_num = int(page_num) start = (page_num - 1) * 5 end = page_num * 5 # 总页码数是"/books/" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >首页</li>'.format(1,1)) for i in range(page_start, page_end+1): tmp = '<li><a href="/books/" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >{}</li>'.format(i, i) html_str_list.append(tmp) html_str_list.append('<li><a href="/books/" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >最后一页</li>'.format(total)) page_html = "".join(html_str_list) return render(request, 'books.html', {'books': all_books, 'total_page': total, 'page_html': page_html})
希望本文所述对大家基于Django框架的Python程序设计有所帮助。