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>

运行结果:

最新文章

  1. iOS 疑难杂症— — 收到推送显示后自动消失的问题
  2. SQL Server中截取字符串常用函数
  3. python 中文乱码问题
  4. 20145204&amp;20145212实验二报告
  5. hdu.5211.Mutiple(数学推导 &amp;&amp; 在logn的时间内求一个数的所有因子)
  6. 在matlab中配置vlfeat
  7. 二叉查找树(binary search tree)详解
  8. double-clicking
  9. 基本包装类型:Boolean、Number 和String
  10. ServiceStack.OrmLite 笔记5 改
  11. Mybatis update In
  12. safari穿越到chrome
  13. linux vi查找命令
  14. 打印HTML页面部分区域javascript代码
  15. php----浅谈一下empty isset is_null的用处
  16. CSS box-flex属性
  17. 序列化日期(yyyy-MM-dd hh:mm:ss)
  18. 老机器安装Centos
  19. 离职有感(CVTE,创业公司,求职...)
  20. 过滤IP地址的正则表达式

热门文章

  1. eclipse更改jdk版本(1.6》1.7 以此类推)
  2. quiver()函数
  3. js正则验证input输入框有空格时提示直接去除空格
  4. Acwing P284 金字塔 题解
  5. DOS窗口操作MySQL数据库
  6. (31)Vue安装
  7. [golang]写了一个可以用 go 来写脚本的工具:gosl
  8. 常用命令备忘 lsof
  9. P1057 传球游戏——小学生dp
  10. Jmeter5.1 Plugins Manager配置dummy使用jp@gc - Dummy Sampler