下面实现分页功能,还是按照固定步骤来。
我先随机插入100条数据。然后分页,每页显示10条数据。
分页类:在前面"08 django管理系统 - 部门管理 - 部门分页"讲到过,代码如下:
python
from django.utils.safestring import mark_safe
class Pagination(object):
def __init__(self, request, queryset, page_size=10, page_param="page", plus=5):
"""
:param request: 请求的对象
:param queryset: 符合条件的数据(根据这个数据给他进行分页处理)
:param page_size: 每页显示多少条数据
:param page_param: 在URL中传递的获取分页的参数,例如:/etty/list/?page=12
:param plus: 显示当前页的 前或后几页(页码)
"""
from django.http.request import QueryDict
import copy
query_dict = copy.deepcopy(request.GET)
query_dict._mutable = True
self.query_dict = query_dict
self.page_param = page_param
page = request.GET.get(page_param, "1")
if page.isdecimal():
page = int(page)
else:
page = 1
self.page = page
self.page_size = page_size
self.start = (page - 1) * page_size
self.end = page * page_size
self.page_queryset = queryset[self.start:self.end]
total_count = queryset.count()
total_page_count, div = divmod(total_count, page_size)
if div:
total_page_count += 1
self.total_page_count = total_page_count
self.plus = plus
def html(self):
# 计算出,显示当前页的前5页、后5页
if self.total_page_count <= 2 * self.plus + 1:
# 数据库中的数据比较少,都没有达到11页。
start_page = 1
end_page = self.total_page_count
else:
# 数据库中的数据比较多 > 11页。
# 当前页<5时(小极值)
if self.page <= self.plus:
start_page = 1
end_page = 2 * self.plus + 1
else:
# 当前页 > 5
# 当前页+5 > 总页面
if (self.page + self.plus) > self.total_page_count:
start_page = self.total_page_count - 2 * self.plus
end_page = self.total_page_count
else:
start_page = self.page - self.plus
end_page = self.page + self.plus
# 页码
page_str_list = []
self.query_dict.setlist(self.page_param, [1])
page_str_list.append('<li><a href="?{}">首页</a></li>'.format(self.query_dict.urlencode()))
# 上一页
if self.page > 1:
self.query_dict.setlist(self.page_param, [self.page - 1])
prev = '<li><a href="?{}">上一页</a></li>'.format(self.query_dict.urlencode())
else:
self.query_dict.setlist(self.page_param, [1])
prev = '<li><a href="?{}">上一页</a></li>'.format(self.query_dict.urlencode())
page_str_list.append(prev)
# 页面
for i in range(start_page, end_page + 1):
self.query_dict.setlist(self.page_param, [i])
if i == self.page:
ele = '<li class="active"><a href="?{}">{}</a></li>'.format(self.query_dict.urlencode(), i)
else:
ele = '<li><a href="?{}">{}</a></li>'.format(self.query_dict.urlencode(), i)
page_str_list.append(ele)
# 下一页
if self.page < self.total_page_count:
self.query_dict.setlist(self.page_param, [self.page + 1])
prev = '<li><a href="?{}">下一页</a></li>'.format(self.query_dict.urlencode())
else:
self.query_dict.setlist(self.page_param, [self.total_page_count])
prev = '<li><a href="?{}">下一页</a></li>'.format(self.query_dict.urlencode())
page_str_list.append(prev)
# 尾页
self.query_dict.setlist(self.page_param, [self.total_page_count])
page_str_list.append('<li><a href="?{}">尾页</a></li>'.format(self.query_dict.urlencode()))
search_string = """
<li>
<form style="float: left;margin-left: -1px" method="get">
<input name="page"
style="position: relative;float:left;display: inline-block;width: 80px;border-radius: 0;"
type="text" class="form-control" placeholder="页码">
<button style="border-radius: 0" class="btn btn-default" type="submit">跳转</button>
</form>
</li>
"""
page_str_list.append(search_string)
page_string = mark_safe("".join(page_str_list))
return page_string
我们去admin_list函数中去修改业务逻辑,并导入utils里的分页类
python
from app01.utils.pagination import Pagination
def admin_list(request):
# return HttpResponse("admin_list is ok")
# 查询所有的数据
queryset = models.Admin.objects.using("default").all()
# 创建分页对象
page_obj = Pagination(request, queryset)
form = AdminModelForm()
# context = {
# "queryset": queryset,
# "form": form
# }
context = {
"form": form,
"queryset": page_obj.page_queryset, # 分完页的数据
"page_html": page_obj.html(), # 分页后的页码
}
return render(request, 'admin_list.html', context)
然后编辑admin_list.html中的table部分
html
<!-- 加上分页 -->
<div class="row">
<ul class="pagination">
{{ page_html }}
</ul>
</div>
完整代码如下:
html
{% extends 'base.html' %}
{% block content %}
<div class="container-fluid">
<div style="margin-bottom: 10px" class="clearfix">
<div class="panel panel-default">
<div class="panel-heading">
<div style="margin-bottom: 18px">
<input type="button" class="btn btn-primary" value="新建管理员" data-toggle="modal"
data-target="#myModal" id="btn_add">
</div>
<div>
<!-- 新建订单弹框 -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-label="Close"><span
aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">新建管理员</h4>
</div>
<div class="modal-body">
<form id="formAdd">
<div class="clearfix">
{% for field in form %}
<div class="col-xs-12">
<div class="form-group"
style="position: relative;margin-bottom: 20px;">
<label>{{ field.label }}</label>
{{ field }}
<span class="error-msg"
style="color: red;position: absolute;">
</span>
</div>
</div>
{% endfor %}
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
<button type="button" class="btn btn-primary" id="btn_save">保存</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="panel-body">
<div style="float: left">
<p>管理员列表</p>
</div>
<!-- Table -->
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>name</th>
<th>password</th>
<th>sex</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for obj in queryset %}
<tr>
<td>{{ obj.id }}</td>
<td>{{ obj.name }}</td>
<td>{{ obj.password }}</td>
<td>{{ obj.get_sex_display }}</td>
<td>
<a class="btn btn-success" href="#" role="button">编辑管理员</a>
<a class="btn btn-danger" href="#" role="button">删除管理员</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% if error %}
<div style="color: red;">
{{ error }}
</div>
{% endif %}
</div>
</div>
</div>
<!-- 加上分页 -->
<div class="row">
<ul class="pagination">
{{ page_html }}
</ul>
</div>
</div>
{% endblock %}
{% block js %}
<script>
// 绑定btn_add的点击事件
$(function () {
// 新增按钮的点击事件
bingBtnAddEvent();
// 保存按钮的点击事件
bindBtnSaveEvent();
})
function bingBtnAddEvent() {
$("#btn_add").click(function () {
// 点击新建管理员,弹出模态框
console.log("click btn_add");
})
}
function bindBtnSaveEvent() {
// 点击之前,清除错误信息
$(".error-msg").empty()
$("#btn_save").click(function () {
{#alert("btn_save clicked! 我被点击拉")#}
// 下面是ajax提交表单数据,提交到后台
// 首先是批量获取表单数据
let formData = $("#formAdd").serialize();
console.log(formData);
// 发送ajax请求
$.ajax({
url: "/admin/add/",
type: "post",
data: formData,
dataType: "json",
success: function (data) {
console.log(data, "我从admin_add函数成功返回");
if (data.status === "True") {
alert("添加成功!")
window.location.reload();
} else {
alert("添加失败!")
// 在弹出框中显示错误信息
console.log(data.error);
// 把错误信息显示在模态框中
$.each(data.error, function (name, error_list) { // name就是字段名,error_list就是错误信息列表
// 根据字段名字,找到对应的input标签,然后显示错误信息
$("#id_" + name).next().text(error_list[0]);
})
}
}
})
})
}
</script>
{% endblock %}
效果如下: