前面的话:
1. 网页引用的bootstrap 中的表格,所以需要引入样式类
2. 第一次写文章,不喜勿喷。有不足的地方,可留言我改正,在此先谢过。
HTML代码:
分页
序号
编号
名字
{% for user in user_list %}
{{ forloop.counter }}
{{ user.id }}
{{ user.name }}
{% endfor %}
views代码:
from django.shortcuts import render, redirect, HttpResponse
from app01 import models
# Create your views here.
def page(request):
# 从url取参数
page_num = request.GET.get("p")
# 求总页数,每页显示10条数据
total_data = models.Books.objects.all().count()
total_page, i = divmod(total_data, 10) # divmod运算可取到整数和余数分别保存在total_page,i 中
try:
page_num = int(page_num)
if page_num > total_page:
page_num = total_page
except Exception as e:
page_num = 1
# 定义两个变量保存起始数据
print(page_num)
data_start = (page_num-1)*10 + 1
data_end = page_num*10
if i:
total_page = total_page + 1 # 判断如有余数,加1页
# 页面上总共展示多少页面
max_page = 7
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
# 前部分
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
# 自己拼接分页的HTTML代码
html_str_list = []
# 加上首页
html_str_list.append('
# 加上上一页
if page_num <= 1:
html_str_list.append(
'
else:
html_str_list.append(
'
page_num - 1))
for i in range(page_start, page_end+1):
# 如果是当前页就加一个active样式类
if i == page_num:
tem = '
else:
tem = '
html_str_list.append(tem)
# 加上下一页
if page_num >= total_page:
html_str_list.append(
'
else:
html_str_list.append(
'
page_num + 1))
# 加最后一页
html_str_list.append('
page_html = "".join(html_str_list)
# all_user = models.UserInfo.objects.all()[10: 20]
all_user = models.Books.objects.filter(id__gte=data_start, id__lte=data_end)
print(all_user)
return render(request, "page.html", {"user_list": all_user, "page_html": page_html})