Python - Django - 简单分页的实现
2024-08-26 18:21:02
models.py:
from django.db import models class Book(models.Model):
title = models.CharField(max_length=32) def __str__(self):
return self.title class Meta:
db_table = "books"
批量创建 106 条数据
import os if __name__ == '__main__':
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite3.settings")
import django
django.setup() from app01 import models # 106 个书籍对象
objs = [models.Book(title="《Python 的故事第{}版》".format(i)) for i in range(116)] # 在数据库中批量创建, 10 次一提交
models.Book.objects.bulk_create(objs, 10)
views.py:
from django.shortcuts import render
from app01 import models def 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)
if m:
total_page += 1 all_book = models.Book.objects.all()[data_start:data_end] # 拼接 html 的分页代码
html_list = []
for i in range(1, total_page+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})
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 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.title }}</td>
</tr>
{% endfor %} </tbody>
</table> <nav aria-label="Page navigation">
<ul class="pagination">
{{ page_html|safe }}
</ul>
</nav> </div> </body>
</html>
运行结果:
最新文章
- iOS 疑难杂症— — 收到推送显示后自动消失的问题
- SQL Server中截取字符串常用函数
- python 中文乱码问题
- 20145204&;20145212实验二报告
- hdu.5211.Mutiple(数学推导 &;&; 在logn的时间内求一个数的所有因子)
- 在matlab中配置vlfeat
- 二叉查找树(binary search tree)详解
- double-clicking
- 基本包装类型:Boolean、Number 和String
- ServiceStack.OrmLite 笔记5 改
- Mybatis update In
- safari穿越到chrome
- linux vi查找命令
- 打印HTML页面部分区域javascript代码
- php----浅谈一下empty isset is_null的用处
- CSS box-flex属性
- 序列化日期(yyyy-MM-dd hh:mm:ss)
- 老机器安装Centos
- 离职有感(CVTE,创业公司,求职...)
- 过滤IP地址的正则表达式