准备
models.py
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=32)
books = models.ManyToManyField(to="Book")
def __str__(self):
return self.name
class Meta:
db_table = "author"
class Book(models.Model):
title = models.CharField(max_length=32)
def __str__(self):
return self.title
class Meta:
db_table = "book"
urls.py
from app01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^books/$', views.books),
]
books.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>
</div>
</body>
</html>
批量插入数据
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "page_demo.settings")
import django
django.setup()
from app01 import models
# 批量创建
# 有100个书籍对象
objs = [models.Book(title="书本{}".format(i)) for i in range(100)]
# 在数据库中批量创建, 10次一提交
models.Book.objects.bulk_create(objs, 10)
展示所有的数据
from django.shortcuts import render
from app01 import models
def books(request):
all_book = models.Book.objects.all()
return render(request, "books.html", {"books": all_book})
需求
现在需求是做一个类似博客园的分页
当点击第一页的时候,URL 显示为 /books/?page=1/
,并显示第一页的数据,一页展示 10 条数据
展示
规律
可以在视图函数里使用切片操作,当要展示第一页的数据,即 1-10 条数据,它的索引是 [0:10]
from django.shortcuts import render
from app01 import models
def books(request):
all_book = models.Book.objects.all()[:10]
return render(request, "books.html", {"books": all_book})
展示第一页的数据,即 11-20 条数据,它的索引是 [10:20]
from django.shortcuts import render
from app01 import models
def books(request):
all_book = models.Book.objects.all()[10:20]
return render(request, "books.html", {"books": all_book})
所以,它的规律是:
from django.shortcuts import render
from app01 import models
def books(request):
# 从URL取参数
page_num = request.GET.get("page")
page_num = int(page_num)
# 定义两个变量保存数据从哪取到哪
data_start = (page_num-1) * 10
data_end = page_num * 10
all_book = models.Book.objects.all()[data_start: data_end]
return render(request, "books.html", {"books": all_book})
增加样式
增加 bootstrap 样式,显示可点击跳转的页码。首先要算出总页码数
可以根据 divmod()
计算,当有 20 条数据,每页展示 10 条,计算出 (2, 0)
,当有 21 条数据,计算出 (2, 1)
,计算出的值里右边的为 0,左边的就是页码数,否则左边的页码数就加一。
然后自己拼接一个 a 标签,将拼接好的传入模板
from django.shortcuts import render
from app01 import models
def books(request):
# 从URL取参数
page_num = request.GET.get("page")
page_num = int(page_num)
# 定义两个变量保存数据从哪取到哪
data_start = (page_num - 1) * 10
data_end = page_num * 10
# 每一页显示多少条数据
per_page = 10
# 总数据是多少
total_count = models.Book.objects.all().count()
# 总共需要多少页码来展示
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_str_list = []
for i in range(1, total_page + 1):
tmp = '<li><a href="/books/?page={0}">{0}</a></li>'.format(i)
html_str_list.append(tmp)
page_html = "".join(html_str_list)
return render(request, "books.html", {"books": all_book, "page_html": page_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">
<li>
<a href="#" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
{{ page_html | safe }}
<li>
<a href="#" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</ul>
</nav>
</div>
</body>
</html>
添加多条数据
以上便是一个简单分页的实现,这是数据比较少的情况,现在向数据库添加至 1000 条数据,再进行页面展示
这显然是不合理的,博客园中页码中间是用省略号,省略号前面的页码一般都为奇数,且始终只有 200 页
所以这里的需求是,展示的页码数固定为 11 页,当前所在页码的前后页码数对称。假如当前在第六页,前面展示五个,后面也展示五个,也就是 1-11 页
有了展示的开始页码和结束页码,拼接 html 代码时也要有所改动
多条数据的首尾页码
然后考虑首尾的问题,如果当前页减一半比 1 小,还是需要固定 1-11 页
如果当前页比 100 大,后面不再显示页码
加上首页、尾页、上一页、下一页
这时,当处于第一页时,上一页不可点击,同样,处于最后一页时,下一页也不可点击。看起来实现了分页的操作,但此时删除至只有一条数据,又出现了页码为负数的情况。
所以要有一个判断
# 页面上总共展示多少页码
max_page = 11
# 当总页码数小于展示的页码数
if total_page < max_page:
max_page = total_page
这样,便能够访问了,再做一些完善,比如用户输入页码数不是数字,或者大于最大的页码数,让当前页码加一个 active 类等。
最终代码
from django.shortcuts import render
from app01 import models
# Create your views here.
def books(request):
# 从URL取参数
page_num = request.GET.get("page")
# 每一页显示多少条数据
per_page = 10
# 总数据是多少
total_count = models.Book.objects.all().count()
# 总共需要多少页码来展示
total_page, m = divmod(total_count, per_page)
if m:
total_page += 1
try:
page_num = int(page_num)
# 如果输入的页码超过了最大的页码数,默认返回最后一页
if page_num > total_page:
page_num = total_page
except Exception as e:
# 当输入的页码不是数字的时候,默认返回第一页的数据
page_num = 1
# 定义两个变量保存数据从哪取到哪
data_start = (page_num - 1) * 10
data_end = page_num * 10
# 页面上总共展示多少页码
max_page = 11
if total_page < max_page:
max_page = total_page
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 + 1
all_book = models.Book.objects.all()[data_start: data_end]
# 拼接分页的html代码
html_str_list = []
# 加上第一页
html_str_list.append('<li><a href="/books/?page=1">首页</a></li>')
# 加上一页,上一页就是当前页减一
# 判断,如果第一页,就没有上一页
if page_num <= 1:
html_str_list.append('<li class="disabled"><a href="#"><span aria-hidden="true">«</span></a></li>')
else:
html_str_list.append(
'<li><a href="/books/?page={}"><span aria-hidden="true">«</span></a></li>'.format(page_num - 1))
for i in range(page_start, page_end + 1):
# 如果是当前页,加一个active样式类
if i == page_num:
tmp = '<li class="active"><a href="/books/?page={0}">{0}</a></li>'.format(i)
else:
tmp = '<li><a href="/books/?page={0}">{0}</a></li>'.format(i)
html_str_list.append(tmp)
# 加下一页,下一页就是当前页加一
# 判断,如果是最后一页,就没有下一页
if page_num >= total_page:
html_str_list.append('<li class="disabled"><a href="#"><span aria-hidden="true">»</span></a></li>')
else:
html_str_list.append(
'<li><a href="/books/?page={}"><span aria-hidden="true">»</span></a></li>'.format(page_num + 1))
# 加最后一页
html_str_list.append('<li><a href="/books/?page={}">尾页</a></li>'.format(total_page))
page_html = "".join(html_str_list)
return render(request, "books.html", {"books": all_book, "page_html": page_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>
封装成通用的模块
class Page():
def __init__(self, page_num, total_count, url_prefix, per_page=10, max_page=11):
"""
:param page_num: 当前页码数
:param total_count: 数据总数
:param url_prefix: a标签href的前缀
:param per_page: 每页显示多少条数据
:param max_page: 页面上最多显示几个页码
"""
self.url_prefix = url_prefix
self.max_page = max_page
# 每一页显示多少条数据
# 总共需要多少页码来展示
total_page, m = divmod(total_count, per_page)
if m:
total_page += 1
self.total_page = total_page
try:
page_num = int(page_num)
# 如果输入的页码超过了最大的页码数,默认返回最后一页
if page_num > total_page:
page_num = total_page
except Exception as e:
# 当输入的页码不是数字的时候,默认返回第一页的数据
page_num = 1
self.page_num = page_num
# 定义两个变量保存数据从哪取到哪
self.data_start = (page_num - 1) * 10
self.data_end = page_num * 10
# 页面上总共展示多少页码
if total_page < self.max_page:
self.max_page = total_page
half_max_page = self.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 = self.max_page
# 如果当前页加一半 比总页码数还大
if page_end >= total_page:
page_end = total_page
page_start = total_page - self.max_page + 1
self.page_start = page_start
self.page_end = page_end
@property
def start(self):
return self.data_start
@property
def end(self):
return self.data_end
def page_html(self):
# 拼接分页的html代码
html_str_list = []
# 加上第一页
html_str_list.append('<li><a href="{}?page=1">首页</a></li>'.format(self.url_prefix))
# 加上一页,上一页就是当前页减一
# 判断,如果第一页,就没有上一页
if self.page_num <= 1:
html_str_list.append('<li class="disabled"><a href="#"><span aria-hidden="true">«</span></a></li>')
else:
html_str_list.append(
'<li><a href="{}?page={}"><span aria-hidden="true">«</span></a></li>'.format(self.url_prefix,
self.page_num - 1))
for i in range(self.page_start, self.page_end + 1):
# 如果是当前页,加一个active样式类
if i == self.page_num:
tmp = '<li class="active"><a href="{0}?page={1}">{1}</a></li>'.format(self.url_prefix, i)
else:
tmp = '<li><a href="{0}?page={1}">{1}</a></li>'.format(self.url_prefix, i)
html_str_list.append(tmp)
# 加下一页,下一页就是当前页加一
# 判断,如果是最后一页,就没有下一页
if self.page_num >= self.total_page:
html_str_list.append('<li class="disabled"><a href="#"><span aria-hidden="true">»</span></a></li>')
else:
html_str_list.append(
'<li><a href="{}?page={}"><span aria-hidden="true">»</span></a></li>'.format(self.url_prefix,
self.page_num + 1))
# 加最后一页
html_str_list.append('<li><a href="{}?page={}">尾页</a></li>'.format(self.url_prefix, self.total_page))
page_html = "".join(html_str_list)
return page_html
from django.shortcuts import render
# Create your views here.
from app01 import models
def books(request):
# 从URL取参数
page_num = request.GET.get("page")
# 调用一个类
from utils.mypage import Page
page_obj = Page(page_num, total_count, per_page=10, url_prefix="/books/", max_page=11)
ret = models.Book.objects.all()[page_obj.start: page_obj.end]
page_html = page_obj.page_html()
return render(request, "books.html", {"books": ret, "page_html": page_html})
def depts(request):
# 从URL中取参数
page_num = request.GET.get("page")
# 总数据是多少
total_count = models.Dept.objects.all().count()
from utils.mypage import Page
page_obj = Page(page_num, total_count, per_page=10, url_prefix="/depts/", max_page=11)
ret = models.Dept.objects.all()[page_obj.start: page_obj.end]
page_html = page_obj.page_html()
return render(request, "dept.html", {"depts": ret, "page_html": page_html})