Django与LayUI 框架实现表格分页

Python
345
0
0
2023-02-13
标签   Django

layui 框架与BootCSS框架相似都属于前端美化框架,区别在于BootCSS更加专业,而LayUI则更多的是面向于后端开发者,所以在组织形式上毅然采用了几年前的以浏览器为宿主的类 AMD 模块管理方式,却又并非受限于 CommonJS 的那些条条框框,它拥有自己的模式,更加轻量和简单。

官方示例1: 简单的页面前端布局。

<link rel="stylesheet" href="https://www.blib.cn/cdn/layui/css/layui.css", media="all">
<script src="https://www.blib.cn/cdn/layui/layui.js"></script>
<table class="layui-hide" id="demo" lay-filter="test"></table>

<script type="text/html" id="barDemo">
  <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail">查看</a>
  <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<script>
layui.use('table', function(){
  var table = layui.table;
  //执行一个 table 实例
  table.render({
    elem: '#demo'
    ,height: 420
    ,url: '/host' //数据接口
    ,title: '用户表'
    ,page: true //开启分页
    ,toolbar: 'default' //开启工具栏,此处显示默认图标,可以自定义模板,详见文档
    ,totalRow: true //开启合计行
    ,cols: [[
      {type: 'checkbox', fixed: 'left'}
      ,{field:'id', title:'ID', width:80,   sort: true}
      ,{field:'hostname', title:'用户名', width:120}
      ,{field:'hostaddr', title:'主机地址',width:120}
      ,{fixed: 'right', title:'操作', toolbar: '#barDemo', width:200}
    ]]
  });
 //监听头工具栏事件
  table.on('toolbar(test)', function(obj){
    var checkStatus = table.checkStatus(obj.config.id)
    ,data = checkStatus.data; //获取选中的数据
    switch(obj.event){
      case 'add':
        layer.msg('添加');
      break;
      case 'update':
        if(data.length === 0){
          layer.msg('请选择一行');
        } else if(data.length > 1){
          layer.msg('只能同时编辑一个');
        } else {
          layer.alert('编辑 [id]:'+ checkStatus.data[0].id);
        }
      break;
      case 'delete':
        if(data.length === 0){
          layer.msg('请选择一行');
        } else {
          layer.msg('删除');
        }
      break;
    };
  });

  //监听行工具事件
  table.on('tool(test)', function(obj){ //注:tool 是工具条事件名,test 是 table 原始容器的属性 lay-filter="对应的值"
    var data = obj.data //获得当前行数据
    ,layEvent = obj.event; //获得 lay-event 对应的值
    if(layEvent === 'detail'){
      layer.msg('查看操作');
    } else if(layEvent === 'del'){
      layer.confirm('真的删除行么', function(index){
        obj.del(); //删除对应行(tr)的DOM结构
        layer.close(index);
        //向服务端发送删除指令
      });
    } else if(layEvent === 'edit'){
      layer.msg('编辑操作');
    }
  });
});
</script>

img

官方示例2: 实现简单的表格布局,可以自定义按钮事件。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Layui</title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <link rel="stylesheet" href="https://www.blib.cn/cdn/layui/css/layui.css", media="all">
  <script src="https://www.blib.cn/cdn/layui/layui.js"></script>
</head>
<body>
 
<table class="layui-hide" id="test" lay-filter="test"></table>
 
<script type="text/html" id="toolbarDemo">
  <div class="layui-btn-container">
    <button class="layui-btn layui-btn-sm" lay-event="getCheckData">获取选中行数据</button>
    <button class="layui-btn layui-btn-sm" lay-event="getCheckLength">获取选中数目</button>
    <button class="layui-btn layui-btn-sm" lay-event="isAll">验证是否全选</button>
  </div>
</script>
 
<script type="text/html" id="barDemo">
  <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
 
<script>
layui.use('table', function(){
  var table = layui.table;
  
  table.render({
    elem: '#test'
    ,url:'/test/table/demo1.json'
    ,toolbar: '#toolbarDemo' //开启头部工具栏,并为其绑定左侧模板
    ,defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义,去除该参数即可
      title: '提示'
      ,layEvent: 'LAYTABLE_TIPS'
      ,icon: 'layui-icon-tips'
    }]
    ,title: '用户数据表'
    ,cols: [[
      {type: 'checkbox', fixed: 'left'}
      ,{field:'id', title:'ID', width:80, fixed: 'left', unresize: true, sort: true}
      ,{field:'username', title:'用户名', width:120, edit: 'text'}
      ,{field:'email', title:'邮箱', width:150, edit: 'text', templet: function(res){
        return '<em>'+ res.email +'</em>'
      }}
      ,{field:'sex', title:'性别', width:80, edit: 'text', sort: true}
      ,{field:'city', title:'城市', width:100}
      ,{field:'sign', title:'签名'}
      ,{field:'experience', title:'积分', width:80, sort: true}
      ,{field:'ip', title:'IP', width:120}
      ,{field:'logins', title:'登入次数', width:100, sort: true}
      ,{field:'joinTime', title:'加入时间', width:120}
      ,{fixed: 'right', title:'操作', toolbar: '#barDemo', width:150}
    ]]
    ,page: true
  });
  
  //头工具栏事件
  table.on('toolbar(test)', function(obj){
    var checkStatus = table.checkStatus(obj.config.id);
    switch(obj.event){
      case 'getCheckData':
        var data = checkStatus.data;
        layer.alert(JSON.stringify(data));
      break;
      case 'getCheckLength':
        var data = checkStatus.data;
        layer.msg('选中了:'+ data.length + ' 个');
      break;
      case 'isAll':
        layer.msg(checkStatus.isAll ? '全选': '未全选');
      break;
      
      //自定义头工具栏右侧图标 - 提示
      case 'LAYTABLE_TIPS':
        layer.alert('这是工具栏右侧自定义的一个图标按钮');
      break;
    };
  });
  
  //监听行工具事件
  table.on('tool(test)', function(obj){
    var data = obj.data;
    //console.log(obj)
    if(obj.event === 'del'){
      layer.confirm('真的删除行么', function(index){
        obj.del();
        layer.close(index);
      });
    } else if(obj.event === 'edit'){
      layer.prompt({
        formType: 2
        ,value: data.email
      }, function(value, index){
        obj.update({
          email: value
        });
        layer.close(index);
      });
    }
  });
});
</script>

</body>
</html>

img

Django 实现表格分页: 接着就是实现分页了,使用layui框架配合Django自带的分页组件,即可完成分页:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://www.blib.cn/cdn/layui/css/layui.css">
    <script type="text/javascript" src="https://www.blib.cn/cdn/layui/layui.js"></script>
</head>
<body>
<table class="layui-hide" id="demo"></table>

    <script type="text/javascript">
    layui.use('table', function(){
      var table = layui.table;
      table.render({
          elem: '#demo',
          url:'/get_page',
          method:'get',
          toolbar: '#toolbarDemo',         // 显示工具条
          request: {
                  pageName: 'pageIndex',  // 页码的参数名称,默认:page
                  limitName: 'pageSize'   // 每页数据量的参数名,默认:limit
          },
          response: {
                  statusName: 'code',     // 规定数据状态的字段名称,默认:code
                  statusCode: 0,          // 规定成功的状态码,默认:0
                  msgName: 'msg',         // 规定状态信息的字段名称,默认:msg
                  countName: 'DataCount', // 规定数据总数的字段名称,默认:count
                  dataName: 'data'        // 规定数据列表的字段名称,默认:data
          }
        ,cols: [[
          {type: 'checkbox', fixed: 'left'},
          {field:'id', title:'主机ID', width:100, sort: true},
          {field:'hostname', title:'主机名称', width:120},
          {field:'hostaddr', title:'主机地址', width:120},
          {field:'hostmode', title:'主机组', width:120},
        ]]
        ,page: {
            layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'],     // 自定义分页布局
            curr: 1,      // 设置默认起始页1
            groups: 10,   //只显示10个连续页码,就是说显示10个可见页其他的省略
            first: false, // 不显示首页
            last: false   // 不显示尾页
        },
        limit: 5,
        limits: [5,10,15,20,25]
      });
    });
    </script>
</body>
</html>

views.py

from django.shortcuts import render,HttpResponse
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
from MyWeb import models
import json

def index(request):
    return render(request,"index.html")

def get_page(request):
    data = models.HostDB.objects.all()
    dataCount = data.count()
    pageIndex = request.GET.get("pageIndex")
    pageSize = request.GET.get("pageSize")
    print("当前索引:{} 当前大小:{}".format(pageIndex,pageSize))
    print("所有记录:{} 数据总条数:{}".format(data,dataCount))

    list = []
    res = []
    for item in data:
        dict = {}
        dict['id'] = item.id
        dict['hostname'] = item.hostname
        dict['hostaddr'] = item.hostaddr
        dict['hostmode'] = item.hostmode
        list.append(dict)

    pageInator = Paginator(list,pageSize)
    context = pageInator.page(pageIndex)
    for item in context:
        res.append(item)
    data = { "code": 0,"msg": "ok","DataCount": dataCount,"data": res }
    return HttpResponse(json.dumps(data))

models.py

from django.db import models

class HostDB(models.Model):
    id = models.AutoField(primary_key=True)
    hostname = models.CharField(max_length=64)
    hostaddr = models.CharField(max_length=64)
    hostmode = models.CharField(max_length=64)

urls.py

from MyWeb import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.index),
    path('get_page/',views.get_page)
]

img

给表格添加搜索功能: 接着我们继续给这个页面添加新功能,这次就先加上一个重载搜索功能吧.

<!--name: index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://www.blib.cn/cdn/layui/css/layui.css">
    <script type="text/javascript" src="https://www.blib.cn/cdn/jquery/jquery3.js"></script>
    <script type="text/javascript" src="https://www.blib.cn/cdn/layui/layui.js"></script>
</head>
<body>


<div class="demoTable">
  搜索名称:
  <div class="layui-inline">
    <input class="layui-input" name="id" id="demoReload" autocomplete="off">
  </div>
  <button class="layui-btn" data-type="reload">搜索</button>
</div>

<table class="layui-hide" id="demo" lay-filter="test"></table>
    <script type="text/javascript">
    layui.use('table', function(){
      var table = layui.table;
      table.render({
          elem: '#demo',
          url:'/get_page',
          method:'get',
          id: 'testReload'
          ,request: {
                  pageName: 'pageIndex',  // 页码的参数名称,默认:page
                  limitName: 'pageSize'   // 每页数据量的参数名,默认:limit
          }
          ,response: {
                  statusName: 'code',     // 规定数据状态的字段名称,默认:code
                  statusCode: 0,          // 规定成功的状态码,默认:0
                  msgName: 'msg',         // 规定状态信息的字段名称,默认:msg
                  countName: 'DataCount', // 规定数据总数的字段名称,默认:count
                  dataName: 'data'        // 规定数据列表的字段名称,默认:data
          }
        ,cols: [[
          {type: 'checkbox', fixed: 'left'},
          {field:'id', title:'主机ID', width:100, sort: true},
          {field:'hostname', title:'主机名称', width:120},
          {field:'hostaddr', title:'主机地址', width:120},
          {field:'hostmode', title:'主机组', width:120},
        ]]
        ,page: {
            layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'],     // 自定义分页布局
            curr: 1,      // 设置默认起始页1
            groups: 10,   //只显示10个连续页码,就是说显示10个可见页其他的省略
            first: false, // 不显示首页
            last: false   // 不显示尾页
        },
        limit: 5,
        limits: [5,10,15,20,25]
      });

    var $ = layui.$, active = {
        reload: function(){
          var demoReload = $('#demoReload');
          console.log(demoReload);
          //执行重载
          table.reload('testReload', {
            url:"/search_page",
            page: {
              curr: 1,
              limits: [1]
            }
            ,where: {
                hostname: demoReload.val()
            }
          }, 'data');
        }
      };
    // 绑定搜索事件
      $('.demoTable .layui-btn').on('click', function(){
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
          });
    });
    </script>
</body>
</html>

views.py

from django.shortcuts import render,HttpResponse
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
from MyWeb import models
import json

def index(request):
    return render(request,"index.html")

def get_page(request):
    data = models.HostDB.objects.all()
    dataCount = data.count()
    pageIndex = request.GET.get("pageIndex")
    pageSize = request.GET.get("pageSize")
    print("当前索引:{} 当前大小:{}".format(pageIndex,pageSize))
    print("所有记录:{} 数据总条数:{}".format(data,dataCount))

    list = []
    res = []
    for item in data:
        dict = {}
        dict['id'] = item.id
        dict['hostname'] = item.hostname
        dict['hostaddr'] = item.hostaddr
        dict['hostmode'] = item.hostmode
        list.append(dict)

    pageInator = Paginator(list,pageSize)
    context = pageInator.page(pageIndex)
    for item in context:
        res.append(item)
    data = { "code": 0,"msg": "ok","DataCount": dataCount,"data": res }
    return HttpResponse(json.dumps(data))

def search_page(request):
    sql = request.GET.get("hostname")
    data = models.HostDB.objects.all().filter(hostname=sql)
    list = []

    for item in data:
        dict = {}
        dict['id'] = item.id
        dict['hostname'] = item.hostname
        dict['hostaddr'] = item.hostaddr
        dict['hostmode'] = item.hostmode
        list.append(dict)

    data = { "code": 0,"msg": "ok","DataCount": 1,"data": list }
    return HttpResponse(json.dumps(data))

urls.py

from MyWeb import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.index),
    path('get_page/',views.get_page),
    path('search_page/',views.search_page)
]

img

给表格添加删除功能: 继续完善删除功能,删除功能就是获取当前表格中的表单ID,然后ajax发后端删除即可。

<!--name: index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://www.blib.cn/cdn/layui/css/layui.css">
    <script type="text/javascript" src="https://www.blib.cn/cdn/jquery/jquery3.js"></script>
    <script type="text/javascript" src="https://www.blib.cn/cdn/layui/layui.js"></script>
</head>
<body>
<div class="demoTable">
    <div class="layui-inline">
        <input class="layui-input" name="id" id="demoReload" autocomplete="off">
    </div>
        <button class="layui-btn" data-type="reload">搜索</button>
</div>

<script type="text/html" id="barDemo">
  <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<table class="layui-hide" id="demo" lay-filter="test"></table>
    <script type="text/javascript">
    layui.use('table', function(){
      var table = layui.table;
      table.render({
          elem: '#demo',
          id: 'testReload',
          url:'/get_page',
          method:'get'
          ,request: {
                  pageName: 'pageIndex',  // 页码的参数名称,默认:page
                  limitName: 'pageSize'   // 每页数据量的参数名,默认:limit
          }
          ,response: {
                  statusName: 'code',     // 规定数据状态的字段名称,默认:code
                  statusCode: 0,          // 规定成功的状态码,默认:0
                  msgName: 'msg',         // 规定状态信息的字段名称,默认:msg
                  countName: 'DataCount', // 规定数据总数的字段名称,默认:count
                  dataName: 'data'        // 规定数据列表的字段名称,默认:data
          }
        ,cols: [[
          {type: 'checkbox', fixed: 'left'},
          {field:'id', title:'主机ID', width:100, sort: true},
          {field:'hostname', title:'主机名称', width:120},
          {field:'hostaddr', title:'主机地址', width:120},
          {field:'hostmode', title:'主机组', width:120},
          {fixed: 'right', title:'操作', toolbar: '#barDemo', width:120}
        ]]
        ,page: {
            layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'],     // 自定义分页布局
            curr: 1,      // 设置默认起始页1
            groups: 10,   // 只显示10个连续页码,就是说显示10个可见页其他的省略
            first: false, // 不显示首页
            last: false   // 不显示尾页
        },
        limit: 5,
        limits: [5,10,15,20,25]
      });
// ------------------------------------------------------------------
// 监听行工具事件:也就是编辑与删除的处理事件
      table.on('tool(test)', function(obj){
        var data = obj.data;
        if(obj.event === 'del'){
          layer.confirm('真的要删除本行数据吗 ?', function(index){
            // console.log("待删除ID: " + obj.data['id']);
           $.ajax({
               url:"/delete_page/",
               type:"get",
               data: {"id":obj.data['id']},
               success:function (recv) {
                   layer.msg("删除完成了..", {icon: 6});
               }
           });
            obj.del();
            layer.close(index);
          });



        } else if(obj.event === 'edit'){
          layer.prompt({
            formType: 2
            ,value: data.email
          }, function(value, index){
            obj.update({
              email: value
            });
            layer.close(index);
          });
        }
      });

        // 搜索后的重载
    var $ = layui.$, active = {
        reload: function(){
          var demoReload = $('#demoReload');
          //执行重载
          table.reload('testReload', {
            url:"/search_page",
            page: {
              curr: 1,
              limits: [1]
            }
            ,where: {
                hostname: demoReload.val()
            }
          }, 'data');
        }
      };
    // ---------------------------------------------------------
    // 绑定搜索事件
      $('.demoTable .layui-btn').on('click', function(){
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
          });
    });
    </script>
</body>
</html>

views.py

def delete_page(request):
    get_id = request.GET.get("id")
    models.HostDB.objects.filter(id=get_id).delete()
    return render(request,"index.html")

url.py

from MyWeb import views

urlpatterns = [
    path('',views.index),
    path('get_page/',views.get_page),
    path('search_page/',views.search_page),
    path('delete_page/',views.delete_page)
]

img

给表格增加编辑功能: 增加编辑功能,用户点击后可自定义编辑页面,并同步更新。

<!--name: index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://www.blib.cn/cdn/layui/css/layui.css">
    <script type="text/javascript" src="https://www.blib.cn/cdn/jquery/jquery3.js"></script>
    <script type="text/javascript" src="https://www.blib.cn/cdn/layui/layui.js"></script>
</head>
<body>
<div class="demoTable">
    <div class="layui-inline">
        <input class="layui-input" name="id" id="demoReload" autocomplete="off">
    </div>
        <button class="layui-btn" data-type="reload">搜索</button>
</div>

<script type="text/html" id="barDemo">
  <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<table class="layui-hide" id="demo" lay-filter="test"></table>

    <script type="text/javascript">
    layui.use('table', function(){
      var table = layui.table;
      table.render({
          elem: '#demo',
          id: 'testReload',
          url:'/get_page',
          method:'get'
          ,request: {
                  pageName: 'pageIndex',  // 页码的参数名称,默认:page
                  limitName: 'pageSize'   // 每页数据量的参数名,默认:limit
          }
          ,response: {
                  statusName: 'code',     // 规定数据状态的字段名称,默认:code
                  statusCode: 0,          // 规定成功的状态码,默认:0
                  msgName: 'msg',         // 规定状态信息的字段名称,默认:msg
                  countName: 'DataCount', // 规定数据总数的字段名称,默认:count
                  dataName: 'data'        // 规定数据列表的字段名称,默认:data
          }
        ,cols: [[
          {type: 'checkbox', fixed: 'left'},
          {field:'id', title:'主机ID', width:100, sort: true},
          {field:'hostname', title:'主机名称', width:120},
          {field:'hostaddr', title:'主机地址', width:120},
          {field:'hostmode', title:'主机组', width:120},
          {fixed: 'right', title:'操作', toolbar: '#barDemo', width:120}
        ]]
        ,page: {
            layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'],     // 自定义分页布局
            curr: 1,      // 设置默认起始页1
            groups: 10,   // 只显示10个连续页码,就是说显示10个可见页其他的省略
            first: false, // 不显示首页
            last: false   // 不显示尾页
        },
        limit: 5,
        limits: [5,10,15,20,25]
      });
// ------------------------------------------------------------------
// 监听行工具事件:也就是编辑与删除的处理事件
      table.on('tool(test)', function(obj){
        var data = obj.data;
        if(obj.event === 'del'){
          layer.confirm('真的要删除本行数据吗 ?', {icon: 3,anim: 2}, function(index){
            // console.log("待删除ID: " + obj.data['id']);
           $.ajax({
               url:"/delete_page/",
               type:"get",
               data: {"id":obj.data['id']},
               success:function (recv) {
                   layer.msg("删除完成了..", {icon: 6});
               }
           });
            obj.del();
            layer.close(index);
          });
        } else if(obj.event === 'edit'){
          layer.prompt({ formType:2, title: "编辑表格",btn:['修改数据','关闭'],anim: 4,
              content:`<div>
                            主机序号: <input type="text" style='display:inline-block' id="id"><br><br>
                            主机名称: <input type="text" style='display:inline-block' id="hostname"><br><br>
                            主机地址: <input type="text" style='display:inline-block' id="hostaddr"><br><br>
                            主机属组: <input type="text" style='display:inline-block' id="hostmode"><br><br>
                       </div>`,
              yes:function (index,layero)
              {
                  console.log("点击yes触发事件:" + index);
                  var id = $("#id").val();
                  var hostname = $("#hostname").val();
                  var hostaddr = $("#hostaddr").val();
                  var hostmode = $("#hostmode").val();
                  $.ajax({
                      url: "/update_page",
                      type: "get",
                      data: {"id": id,
                              "hostname": hostname,
                              "hostaddr": hostaddr,
                              "hostmode": hostmode },
                      success:function (recv) {
                        // 修改完成后,本地直接更新数据,这样就无需刷新一次了
                          obj.update({
                              hostname: hostname,
                              hostaddr: hostaddr,
                              hostmode: hostmode
                          });
                          layer.msg("修改完成了..", {icon: 6});
                          layer.close(index);
                      }
                  });
              }
          });
              $("#id").val(data.id);
              $("#hostname").val(data.hostname);
              $("#hostaddr").val(data.hostaddr);
              $("#hostmode").val(data.hostmode);
        }
      });

        // 搜索后的重载,也就是找到数据以后直接更新
      var $ = layui.$, active = {
        reload: function(){
          var demoReload = $('#demoReload');
          //执行重载
          table.reload('testReload', {
            url:"/search_page",
            page: {
              curr: 1,
              limits: [1]
            }
            ,where: {
                hostname: demoReload.val()
            }
          });
        }
      };
    // ---------------------------------------------------------
    // 绑定搜索事件
      $('.demoTable .layui-btn').on('click', function(){
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
          });
    });
    </script>
</body>
</html>

views.py

from django.shortcuts import render,HttpResponse
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
from MyWeb import models
import json

def index(request):
    return render(request,"index.html")

def get_page(request):
    data = models.HostDB.objects.all()
    dataCount = data.count()
    pageIndex = request.GET.get("pageIndex")
    pageSize = request.GET.get("pageSize")
    print("当前索引:{} 当前大小:{}".format(pageIndex,pageSize))
    print("所有记录:{} 数据总条数:{}".format(data,dataCount))

    list = []
    res = []
    for item in data:
        dict = {}
        dict['id'] = item.id
        dict['hostname'] = item.hostname
        dict['hostaddr'] = item.hostaddr
        dict['hostmode'] = item.hostmode
        list.append(dict)

    pageInator = Paginator(list,pageSize)
    context = pageInator.page(pageIndex)
    for item in context:
        res.append(item)
    data = { "code": 0,"msg": "ok","DataCount": dataCount,"data": res }
    return HttpResponse(json.dumps(data))

def search_page(request):
    sql = request.GET.get("hostname")
    data = models.HostDB.objects.all().filter(hostname=sql)
    list = []
    for item in data:
        dict = {}
        dict['id'] = item.id
        dict['hostname'] = item.hostname
        dict['hostaddr'] = item.hostaddr
        dict['hostmode'] = item.hostmode
        list.append(dict)

    data = { "code": 0,"msg": "ok","DataCount": 1,"data": list }
    return HttpResponse(json.dumps(data))

def delete_page(request):
    get_id = request.GET.get("id")
    models.HostDB.objects.filter(id=get_id).delete()
    return render(request,"index.html")

def update_page(request):
    get_id = request.GET.get("id")
    get_hostname = request.GET.get("hostname")
    get_hostaddr = request.GET.get("hostaddr")
    get_hostmode = request.GET.get("hostmode")

    print(get_hostmode)
    obj = models.HostDB.objects.get(id=get_id)
    obj.hostname = get_hostname
    obj.hostaddr = get_hostaddr
    obj.hostmode = get_hostmode
    obj.save()
    return render(request,"index.html")

urls.py

from MyWeb import views

urlpatterns = [
    path('',views.index),
    path('get_page/',views.get_page),
    path('search_page/',views.search_page),
    path('delete_page/',views.delete_page),
    path("update_page/",views.update_page)
]

img

如下是全部完整代码。

利用layui框架实现分页: layui是一个完整的前端开发框架,利用它可以快速构建分页应用,比BootStrap更加灵活.

# models.py
from django.db import models

class HostDB(models.Model):
    id = models.AutoField(primary_key=True)
    hostname = models.CharField(max_length=64)
    hostaddr = models.CharField(max_length=64)
    hostmode = models.CharField(max_length=64)
<!--name: index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://lyshark.com/cdn/layui/css/layui.css">
    <script type="text/javascript" src="https://lyshark.com/cdn/layui/layui.js"></script>
</head>
<body>
<table class="layui-hide" id="demo"></table>

    <script type="text/javascript">
    layui.use('table', function(){
      var table = layui.table;
      table.render({
          elem: '#demo',
          url:'/get_page',
          method:'get',
          toolbar: '#toolbarDemo'         // 显示工具条
          ,request: {
                  pageName: 'pageIndex',  // 页码的参数名称,默认:page
                  limitName: 'pageSize'   // 每页数据量的参数名,默认:limit
          }
          ,response: {
                  statusName: 'code',     // 规定数据状态的字段名称,默认:code
                  statusCode: 0,          // 规定成功的状态码,默认:0
                  msgName: 'msg',         // 规定状态信息的字段名称,默认:msg
                  countName: 'DataCount', // 规定数据总数的字段名称,默认:count
                  dataName: 'data'        // 规定数据列表的字段名称,默认:data
          }
        ,cols: [[
          {type: 'checkbox', fixed: 'left'},
          {field:'id', title:'主机ID', width:100, sort: true},
          {field:'hostname', title:'主机名称', width:120},
          {field:'hostaddr', title:'主机地址', width:120},
          {field:'hostmode', title:'主机组', width:120},
        ]]
        ,page: {
            layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'],     // 自定义分页布局
            curr: 1,      // 设置默认起始页1
            groups: 10,   //只显示10个连续页码,就是说显示10个可见页其他的省略
            first: false, // 不显示首页
            last: false   // 不显示尾页
        },
        limit: 5,
        limits: [5,10,15,20,25]
      });
    });
    </script>
</body>
</html>
# views.py

from django.shortcuts import render,HttpResponse
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
from MyWeb import models
import json

def index(request):
    return render(request,"index.html")

def get_page(request):
    data = models.HostDB.objects.all()
    dataCount = data.count()
    pageIndex = request.GET.get("pageIndex")
    pageSize = request.GET.get("pageSize")
    print("当前索引:{} 当前大小:{}".format(pageIndex,pageSize))
    print("所有记录:{} 数据总条数:{}".format(data,dataCount))

    # 将数据组装成字典后放入data_list列表
    data_list,ref_data = [],[]
    for item in data:
        dict = { 'id':item.id , 'hostname':item.hostname, 'hostaddr':item.hostaddr, 'hostmode':item.hostmode }
        data_list.append(dict)

    # 使用分页器分页
    pageInator = Paginator(data_list,pageSize)
    context = pageInator.page(pageIndex)
    for item in context:
        ref_data.append(item)
    # 返回分页格式
    data = { "code": 0,"msg": "ok","DataCount": dataCount,"data": ref_data }
    return HttpResponse(json.dumps(data))
# name: url.py
from MyWeb import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.index),
    path('get_page/',views.get_page)
]

layui实现完整表格分页: 通过使用layui框架完成的一个相对完整的表格分页,可用于生产环境.

<!--name: index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://lyshark.com/cdn/layui/css/layui.css">
    <script type="text/javascript" src="https://lyshark.com/cdn/jquery/jquery3.js"></script>
    <script type="text/javascript" src="https://lyshark.com/cdn/layui/layui.js"></script>
</head>
<body>
<div class="demoTable">
    <div class="layui-inline">
        <input class="layui-input" name="id" id="demoReload" autocomplete="off">
    </div>
        <button class="layui-btn" data-type="reload">搜索</button>
</div>

<script type="text/html" id="barDemo">
  <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<table class="layui-hide" id="demo" lay-filter="test"></table>

    <script type="text/javascript">
    layui.use('table', function(){
      var table = layui.table;
      table.render({
          elem: '#demo',
          id: 'testReload',
          url:'/get_page',
          method:'get'
          ,request: {
                  pageName: 'pageIndex',  // 页码的参数名称,默认:page
                  limitName: 'pageSize'   // 每页数据量的参数名,默认:limit
          }
          ,response: {
                  statusName: 'code',     // 规定数据状态的字段名称,默认:code
                  statusCode: 0,          // 规定成功的状态码,默认:0
                  msgName: 'msg',         // 规定状态信息的字段名称,默认:msg
                  countName: 'DataCount', // 规定数据总数的字段名称,默认:count
                  dataName: 'data'        // 规定数据列表的字段名称,默认:data
          }
        ,cols: [[
          {type: 'checkbox', fixed: 'left'},
          {field:'id', title:'主机ID', width:100, sort: true},
          {field:'hostname', title:'主机名称', width:120},
          {field:'hostaddr', title:'主机地址', width:120},
          {field:'hostmode', title:'主机组', width:120},
          {fixed: 'right', title:'操作', toolbar: '#barDemo', width:120}
        ]]
        ,page: {
            layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'],     // 自定义分页布局
            curr: 1,      // 设置默认起始页1
            groups: 10,   // 只显示10个连续页码,就是说显示10个可见页其他的省略
            first: false, // 不显示首页
            last: false   // 不显示尾页
        },
        limit: 5,
        limits: [5,10,15,20,25]
      });
// ------------------------------------------------------------------
// 监听行工具事件:也就是编辑与删除的处理事件
      table.on('tool(test)', function(obj){
        var data = obj.data;
        if(obj.event === 'del'){
          layer.confirm('真的要删除本行数据吗 ?', {icon: 3,anim: 2}, function(index){
            // console.log("待删除ID: " + obj.data['id']);
           $.ajax({
               url:"/delete_page/",
               type:"get",
               data: {"id":obj.data['id']},
               success:function (recv) {
                   layer.msg("删除完成了..", {icon: 6});
               }
           });
            obj.del();
            layer.close(index);
          });
        } else if(obj.event === 'edit'){
          layer.prompt({ formType:2, title: "编辑表格",btn:['修改数据','关闭'],anim: 4,
              content:`<div>
                            主机序号: <input type="text" style='display:inline-block' id="id"><br><br>
                            主机名称: <input type="text" style='display:inline-block' id="hostname"><br><br>
                            主机地址: <input type="text" style='display:inline-block' id="hostaddr"><br><br>
                            主机属组: <input type="text" style='display:inline-block' id="hostmode"><br><br>
                       </div>`,
              yes:function (index,layero)
              {
                  console.log("点击yes触发事件:" + index);
                  var id = $("#id").val();
                  var hostname = $("#hostname").val();
                  var hostaddr = $("#hostaddr").val();
                  var hostmode = $("#hostmode").val();
                  $.ajax({
                      url: "/update_page",
                      type: "get",
                      data: {"id": id,
                              "hostname": hostname,
                              "hostaddr": hostaddr,
                              "hostmode": hostmode },
                      success:function (recv) {
                        // 修改完成后,本地直接更新数据,这样就无需刷新一次了
                          obj.update({
                              hostname: hostname,
                              hostaddr: hostaddr,
                              hostmode: hostmode
                          });
                          layer.msg("修改完成了..", {icon: 6});
                          layer.close(index);
                      }
                  });
              }
          });
              $("#id").val(data.id);
              $("#hostname").val(data.hostname);
              $("#hostaddr").val(data.hostaddr);
              $("#hostmode").val(data.hostmode);
        }
      });

        // 搜索后的重载,也就是找到数据以后直接更新
      var $ = layui.$, active = {
        reload: function(){
          var demoReload = $('#demoReload');
          //执行重载
          table.reload('testReload', {
            url:"/search_page",
            page: {
              curr: 1,
              limits: [1]
            }
            ,where: {
                hostname: demoReload.val()
            }
          });
        }
      };
    // ---------------------------------------------------------
    // 绑定搜索事件
      $('.demoTable .layui-btn').on('click', function(){
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
          });
    });
    </script>
</body>
</html>
# name:views.py

from django.shortcuts import render,HttpResponse
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
from MyWeb import models
import json

def index(request):
    return render(request,"index.html")

def get_page(request):
    data = models.HostDB.objects.all()
    dataCount = data.count()
    pageIndex = request.GET.get("pageIndex")
    pageSize = request.GET.get("pageSize")
    print("当前索引:{} 当前大小:{}".format(pageIndex,pageSize))
    print("所有记录:{} 数据总条数:{}".format(data,dataCount))

    list = []
    res = []
    for item in data:
        dict = {}
        dict['id'] = item.id
        dict['hostname'] = item.hostname
        dict['hostaddr'] = item.hostaddr
        dict['hostmode'] = item.hostmode
        list.append(dict)

    pageInator = Paginator(list,pageSize)
    context = pageInator.page(pageIndex)
    for item in context:
        res.append(item)
    data = { "code": 0,"msg": "ok","DataCount": dataCount,"data": res }
    return HttpResponse(json.dumps(data))

def search_page(request):
    sql = request.GET.get("hostname")
    data = models.HostDB.objects.all().filter(hostname=sql)
    list = []
    for item in data:
        dict = {}
        dict['id'] = item.id
        dict['hostname'] = item.hostname
        dict['hostaddr'] = item.hostaddr
        dict['hostmode'] = item.hostmode
        list.append(dict)

    data = { "code": 0,"msg": "ok","DataCount": 1,"data": list }
    return HttpResponse(json.dumps(data))

def delete_page(request):
    get_id = request.GET.get("id")
    models.HostDB.objects.filter(id=get_id).delete()
    return render(request,"index.html")

def update_page(request):
    get_id = request.GET.get("id")
    get_hostname = request.GET.get("hostname")
    get_hostaddr = request.GET.get("hostaddr")
    get_hostmode = request.GET.get("hostmode")

    print(get_hostmode)
    obj = models.HostDB.objects.get(id=get_id)
    obj.hostname = get_hostname
    obj.hostaddr = get_hostaddr
    obj.hostmode = get_hostmode
    obj.save()
    return render(request,"index.html")
# name: urls.py

from MyWeb import views

urlpatterns = [
    path('',views.index),
    path('get_page/',views.get_page),
    path('search_page/',views.search_page),
    path('delete_page/',views.delete_page),
    path("update_page/",views.update_page)
]

代码总结

实现简单表格分页: layui 是一个完整的前端开发框架,利用它可以快速构建分页应用,比BootStrap更加灵活.

首先我们创建一个models.py 规划好我们的表结构,并插入一些测试数据.

# models.py
from django.db import models

class HostDB(models.Model):
    id = models.AutoField(primary_key=True)
    hostname = models.CharField(max_length=64)
    hostaddr = models.CharField(max_length=64)
    hostmode = models.CharField(max_length=64)

插入完成数据后,我们接着创建前端页面并引用LayUi框架.

<!--name: index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://www.layuicdn.com/layui-v2.5.6/css/layui.css">
    <script type="text/javascript" src="https://www.layuicdn.com/layui-v2.5.6/layui.js"></script>
</head>
<body>
<table class="layui-hide" id="demo"></table>
    <script type="text/javascript">
    layui.use('table', function(){
      var table = layui.table;
      table.render({
          elem: '#demo',
          url:'/get_page',
          method:'get',
          toolbar: '#toolbarDemo'         // 显示工具条
          ,request: {
                  pageName: 'pageIndex',  // 页码的参数名称,默认:page
                  limitName: 'pageSize'   // 每页数据量的参数名,默认:limit
          }
          ,response: {
                  statusName: 'code',     // 规定数据状态的字段名称,默认:code
                  statusCode: 0,          // 规定成功的状态码,默认:0
                  msgName: 'msg',         // 规定状态信息的字段名称,默认:msg
                  countName: 'DataCount', // 规定数据总数的字段名称,默认:count
                  dataName: 'data'        // 规定数据列表的字段名称,默认:data
          }
        ,cols: [[
          {type: 'checkbox', fixed: 'left'},
          {field:'id', title:'主机ID', width:100, sort: true},
          {field:'hostname', title:'主机名称', width:120},
          {field:'hostaddr', title:'主机地址', width:120},
          {field:'hostmode', title:'主机组', width:120},
        ]]
        ,page: {
            layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'],     // 自定义分页布局
            curr: 1,      // 设置默认起始页1
            groups: 10,   //只显示10个连续页码,就是说显示10个可见页其他的省略
            first: false, // 不显示首页
            last: false   // 不显示尾页
        },
        limit: 5,
        limits: [5,10,15,20,25]
      });
    });
    </script>
</body>
</html>

接着创建view.py视图文件,并在后台做好分页处理.

# views.py

from django.shortcuts import render,HttpResponse
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
from MyWeb import models
import json

def index(request):
    return render(request,"index.html")

def get_page(request):
    data = models.HostDB.objects.all()
    dataCount = data.count()
    pageIndex = request.GET.get("pageIndex")
    pageSize = request.GET.get("pageSize")
    print("当前索引:{} 当前大小:{}".format(pageIndex,pageSize))
    print("所有记录:{} 数据总条数:{}".format(data,dataCount))

    # 将数据组装成字典后放入data_list列表
    data_list,ref_data = [],[]
    for item in data:
        dict = { 'id':item.id , 'hostname':item.hostname, 'hostaddr':item.hostaddr, 'hostmode':item.hostmode }
        data_list.append(dict)

    # 使用分页器分页
    pageInator = Paginator(data_list,pageSize)
    context = pageInator.page(pageIndex)
    for item in context:
        ref_data.append(item)
    # 返回分页格式
    data = { "code": 0,"msg": "ok","DataCount": dataCount,"data": ref_data }
    return HttpResponse(json.dumps(data))

最后增加路由映射记录,记录值如下所示.

# name: url.py
from django.contrib import admin
from django.urls import path
from MyWeb import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.index),
    path('get_page/',views.get_page)
]

img

给表格添加搜索功能: 接着我们继续给这个页面添加新功能,这次就先加上一个重载搜索功能吧,前端代码只需要稍微修改一下.

<!--name: index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://www.layuicdn.com/layui-v2.5.6/css/layui.css">
    <script type="text/javascript" src="https://www.layuicdn.com/layui-v2.5.6/layui.js"></script>
    <script src="https://code.jquery.com/jquery-3.2.0.min.js"></script>
</head>
<body>

<div class="demoTable">
  搜索名称:
  <div class="layui-inline">
    <input class="layui-input" name="id" id="demoReload" autocomplete="off">
  </div>
  <button class="layui-btn" data-type="reload">搜索</button>
</div>

<table class="layui-hide" id="demo" lay-filter="test"></table>
    <script type="text/javascript">
    layui.use('table', function(){
      var table = layui.table;
      table.render({
          elem: '#demo',
          url:'/get_page',
          method:'get',
          id: 'testReload'
          ,request: {
                  pageName: 'pageIndex',  // 页码的参数名称,默认:page
                  limitName: 'pageSize'   // 每页数据量的参数名,默认:limit
          }
          ,response: {
                  statusName: 'code',     // 规定数据状态的字段名称,默认:code
                  statusCode: 0,          // 规定成功的状态码,默认:0
                  msgName: 'msg',         // 规定状态信息的字段名称,默认:msg
                  countName: 'DataCount', // 规定数据总数的字段名称,默认:count
                  dataName: 'data'        // 规定数据列表的字段名称,默认:data
          }
        ,cols: [[
          {type: 'checkbox', fixed: 'left'},
          {field:'id', title:'主机ID', width:100, sort: true},
          {field:'hostname', title:'主机名称', width:120},
          {field:'hostaddr', title:'主机地址', width:120},
          {field:'hostmode', title:'主机组', width:120},
        ]]
        ,page: {
            layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'],     // 自定义分页布局
            curr: 1,      // 设置默认起始页1
            groups: 10,   //只显示10个连续页码,就是说显示10个可见页其他的省略
            first: false, // 不显示首页
            last: false   // 不显示尾页
        },
        limit: 5,
        limits: [5,10,15,20,25]
      });

    var $ = layui.$, active = {
        reload: function(){
          var demoReload = $('#demoReload');
          console.log(demoReload);
          //执行重载
          table.reload('testReload', {
            url:"/search_page",
            page: {
              curr: 1,
              limits: [1]
            }
            ,where: {
                hostname: demoReload.val()
            }
          }, 'data');
        }
      };
    // 绑定搜索事件
      $('.demoTable .layui-btn').on('click', function(){
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
          });
    });
    </script>
</body>
</html>

然后修改视图层views.py增加搜索方法的实现过程.

from django.shortcuts import render,HttpResponse
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
from MyWeb import models
import json

def index(request):
    return render(request,"index.html")

def get_page(request):
    data = models.HostDB.objects.all()
    dataCount = data.count()
    pageIndex = request.GET.get("pageIndex")
    pageSize = request.GET.get("pageSize")
    print("当前索引:{} 当前大小:{}".format(pageIndex,pageSize))
    print("所有记录:{} 数据总条数:{}".format(data,dataCount))

    list = []
    res = []
    for item in data:
        dict = {}
        dict['id'] = item.id
        dict['hostname'] = item.hostname
        dict['hostaddr'] = item.hostaddr
        dict['hostmode'] = item.hostmode
        list.append(dict)

    pageInator = Paginator(list,pageSize)
    context = pageInator.page(pageIndex)
    for item in context:
        res.append(item)
    data = { "code": 0,"msg": "ok","DataCount": dataCount,"data": res }
    return HttpResponse(json.dumps(data))

def search_page(request):
    sql = request.GET.get("hostname")
    data = models.HostDB.objects.all().filter(hostname=sql)
    list = []

    for item in data:
        dict = {}
        dict['id'] = item.id
        dict['hostname'] = item.hostname
        dict['hostaddr'] = item.hostaddr
        dict['hostmode'] = item.hostmode
        list.append(dict)

    data = { "code": 0,"msg": "ok","DataCount": 1,"data": list }
    return HttpResponse(json.dumps(data))

路由层也需要增加搜索接口.

# name: url.py
from django.contrib import admin
from django.urls import path
from MyWeb import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.index),
    path('get_page/',views.get_page),
    path('search_page/',views.search_page)
]

img

添加删除功能: 继续完善删除功能,删除功能就是获取当前表格中的表单ID,然后ajax发后端删除即可。 先来把前端代码改一下.

<!--name: index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://www.layuicdn.com/layui-v2.5.6/css/layui.css">
    <script type="text/javascript" src="https://www.layuicdn.com/layui-v2.5.6/layui.js"></script>
    <script src="https://code.jquery.com/jquery-3.2.0.min.js"></script>
</head>
<body>
<div class="demoTable">
    <div class="layui-inline">
        <input class="layui-input" name="id" id="demoReload" autocomplete="off">
    </div>
        <button class="layui-btn" data-type="reload">搜索</button>
</div>

<script type="text/html" id="barDemo">
  <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<table class="layui-hide" id="demo" lay-filter="test"></table>
    <script type="text/javascript">
    layui.use('table', function(){
      var table = layui.table;
      table.render({
          elem: '#demo',
          id: 'testReload',
          url:'/get_page',
          method:'get'
          ,request: {
                  pageName: 'pageIndex',  // 页码的参数名称,默认:page
                  limitName: 'pageSize'   // 每页数据量的参数名,默认:limit
          }
          ,response: {
                  statusName: 'code',     // 规定数据状态的字段名称,默认:code
                  statusCode: 0,          // 规定成功的状态码,默认:0
                  msgName: 'msg',         // 规定状态信息的字段名称,默认:msg
                  countName: 'DataCount', // 规定数据总数的字段名称,默认:count
                  dataName: 'data'        // 规定数据列表的字段名称,默认:data
          }
        ,cols: [[
          {type: 'checkbox', fixed: 'left'},
          {field:'id', title:'主机ID', width:100, sort: true},
          {field:'hostname', title:'主机名称', width:120},
          {field:'hostaddr', title:'主机地址', width:120},
          {field:'hostmode', title:'主机组', width:120},
          {fixed: 'right', title:'操作', toolbar: '#barDemo', width:120}
        ]]
        ,page: {
            layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'],     // 自定义分页布局
            curr: 1,      // 设置默认起始页1
            groups: 10,   // 只显示10个连续页码,就是说显示10个可见页其他的省略
            first: false, // 不显示首页
            last: false   // 不显示尾页
        },
        limit: 5,
        limits: [5,10,15,20,25]
      });
// ------------------------------------------------------------------
// 监听行工具事件:也就是编辑与删除的处理事件
      table.on('tool(test)', function(obj){
        var data = obj.data;
        if(obj.event === 'del'){
          layer.confirm('真的要删除本行数据吗 ?', function(index){
            // console.log("待删除ID: " + obj.data['id']);
           $.ajax({
               url:"/delete_page/",
               type:"get",
               data: {"id":obj.data['id']},
               success:function (recv) {
                   layer.msg("删除完成了..", {icon: 6});
               }
           });
            obj.del();
            layer.close(index);
          });
        } else if(obj.event === 'edit'){
          layer.prompt({
            formType: 2
            ,value: data.email
          }, function(value, index){
            obj.update({
              email: value
            });
            layer.close(index);
          });
        }
      });

        // 搜索后的重载
    var $ = layui.$, active = {
        reload: function(){
          var demoReload = $('#demoReload');
          //执行重载
          table.reload('testReload', {
            url:"/search_page",
            page: {
              curr: 1,
              limits: [1]
            }
            ,where: {
                hostname: demoReload.val()
            }
          }, 'data');
        }
      };
    // ---------------------------------------------------------
    // 绑定搜索事件
      $('.demoTable .layui-btn').on('click', function(){
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
          });
    });
    </script>
</body>
</html>

接着修改视图层,增加删除方法的具体实现细节.

from django.shortcuts import render,HttpResponse
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
from MyWeb import models
import json

def index(request):
    return render(request,"index.html")

def get_page(request):
    data = models.HostDB.objects.all()
    dataCount = data.count()
    pageIndex = request.GET.get("pageIndex")
    pageSize = request.GET.get("pageSize")
    print("当前索引:{} 当前大小:{}".format(pageIndex,pageSize))
    print("所有记录:{} 数据总条数:{}".format(data,dataCount))

    list = []
    res = []
    for item in data:
        dict = {}
        dict['id'] = item.id
        dict['hostname'] = item.hostname
        dict['hostaddr'] = item.hostaddr
        dict['hostmode'] = item.hostmode
        list.append(dict)

    pageInator = Paginator(list,pageSize)
    context = pageInator.page(pageIndex)
    for item in context:
        res.append(item)
    data = { "code": 0,"msg": "ok","DataCount": dataCount,"data": res }
    return HttpResponse(json.dumps(data))

def search_page(request):
    sql = request.GET.get("hostname")
    data = models.HostDB.objects.all().filter(hostname=sql)
    list = []

    for item in data:
        dict = {}
        dict['id'] = item.id
        dict['hostname'] = item.hostname
        dict['hostaddr'] = item.hostaddr
        dict['hostmode'] = item.hostmode
        list.append(dict)

    data = { "code": 0,"msg": "ok","DataCount": 1,"data": list }
    return HttpResponse(json.dumps(data))

def delete_page(request):
    get_id = request.GET.get("id")
    models.HostDB.objects.filter(id=get_id).delete()
    return render(request,"index.html")

路由层增加删除视图.

# name: url.py

from django.contrib import admin
from django.urls import path
from MyWeb import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.index),
    path('get_page/',views.get_page),
    path('search_page/',views.search_page),
    path('delete_page/',views.delete_page)
]

img

增加编辑功能: 增加编辑功能,用户点击后可自定义编辑页面,并同步更新,先修改前端代码。

<!--name: index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://www.layuicdn.com/layui-v2.5.6/css/layui.css">
    <script type="text/javascript" src="https://www.layuicdn.com/layui-v2.5.6/layui.js"></script>
    <script src="https://code.jquery.com/jquery-3.2.0.min.js"></script>
</head>
<body>
<div class="demoTable">
    <div class="layui-inline">
        <input class="layui-input" name="id" id="demoReload" autocomplete="off">
    </div>
        <button class="layui-btn" data-type="reload">搜索</button>
</div>

<script type="text/html" id="barDemo">
  <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<table class="layui-hide" id="demo" lay-filter="test"></table>

    <script type="text/javascript">
    layui.use('table', function(){
      var table = layui.table;
      table.render({
          elem: '#demo',
          id: 'testReload',
          url:'/get_page',
          method:'get'
          ,request: {
                  pageName: 'pageIndex',  // 页码的参数名称,默认:page
                  limitName: 'pageSize'   // 每页数据量的参数名,默认:limit
          }
          ,response: {
                  statusName: 'code',     // 规定数据状态的字段名称,默认:code
                  statusCode: 0,          // 规定成功的状态码,默认:0
                  msgName: 'msg',         // 规定状态信息的字段名称,默认:msg
                  countName: 'DataCount', // 规定数据总数的字段名称,默认:count
                  dataName: 'data'        // 规定数据列表的字段名称,默认:data
          }
        ,cols: [[
          {type: 'checkbox', fixed: 'left'},
          {field:'id', title:'主机ID', width:100, sort: true},
          {field:'hostname', title:'主机名称', width:120},
          {field:'hostaddr', title:'主机地址', width:120},
          {field:'hostmode', title:'主机组', width:120},
          {fixed: 'right', title:'操作', toolbar: '#barDemo', width:120}
        ]]
        ,page: {
            layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'],     // 自定义分页布局
            curr: 1,      // 设置默认起始页1
            groups: 10,   // 只显示10个连续页码,就是说显示10个可见页其他的省略
            first: false, // 不显示首页
            last: false   // 不显示尾页
        },
        limit: 5,
        limits: [5,10,15,20,25]
      });
// ------------------------------------------------------------------
// 监听行工具事件:也就是编辑与删除的处理事件
      table.on('tool(test)', function(obj){
        var data = obj.data;
        if(obj.event === 'del'){
          layer.confirm('真的要删除本行数据吗 ?', {icon: 3,anim: 2}, function(index){
            // console.log("待删除ID: " + obj.data['id']);
           $.ajax({
               url:"/delete_page/",
               type:"get",
               data: {"id":obj.data['id']},
               success:function (recv) {
                   layer.msg("删除完成了..", {icon: 6});
               }
           });
            obj.del();
            layer.close(index);
          });
        } else if(obj.event === 'edit'){
          layer.prompt({ formType:2, title: "编辑表格",btn:['修改数据','关闭'],anim: 4,
              content:`<div>
                            主机序号: <input type="text" style='display:inline-block' id="id"><br><br>
                            主机名称: <input type="text" style='display:inline-block' id="hostname"><br><br>
                            主机地址: <input type="text" style='display:inline-block' id="hostaddr"><br><br>
                            主机属组: <input type="text" style='display:inline-block' id="hostmode"><br><br>
                       </div>`,
              yes:function (index,layero)
              {
                  console.log("点击yes触发事件:" + index);
                  var id = $("#id").val();
                  var hostname = $("#hostname").val();
                  var hostaddr = $("#hostaddr").val();
                  var hostmode = $("#hostmode").val();
                  $.ajax({
                      url: "/update_page",
                      type: "get",
                      data: {"id": id,
                              "hostname": hostname,
                              "hostaddr": hostaddr,
                              "hostmode": hostmode },
                      success:function (recv) {
                        // 修改完成后,本地直接更新数据,这样就无需刷新一次了
                          obj.update({
                              hostname: hostname,
                              hostaddr: hostaddr,
                              hostmode: hostmode
                          });
                          layer.msg("修改完成了..", {icon: 6});
                          layer.close(index);
                      }
                  });
              }
          });
              $("#id").val(data.id);
              $("#hostname").val(data.hostname);
              $("#hostaddr").val(data.hostaddr);
              $("#hostmode").val(data.hostmode);
        }
      });

        // 搜索后的重载,也就是找到数据以后直接更新
      var $ = layui.$, active = {
        reload: function(){
          var demoReload = $('#demoReload');
          //执行重载
          table.reload('testReload', {
            url:"/search_page",
            page: {
              curr: 1,
              limits: [1]
            }
            ,where: {
                hostname: demoReload.val()
            }
          });
        }
      };
    // ---------------------------------------------------------
    // 绑定搜索事件
      $('.demoTable .layui-btn').on('click', function(){
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
          });
    });
    </script>
</body>
</html>

接着修改视图层,此处只需要增加一个 update_page 函数来实现修改即可。

from django.shortcuts import render,HttpResponse
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
from MyWeb import models
import json

def index(request):
    return render(request,"index.html")

def get_page(request):
    data = models.HostDB.objects.all()
    dataCount = data.count()
    pageIndex = request.GET.get("pageIndex")
    pageSize = request.GET.get("pageSize")
    print("当前索引:{} 当前大小:{}".format(pageIndex,pageSize))
    print("所有记录:{} 数据总条数:{}".format(data,dataCount))

    list = []
    res = []
    for item in data:
        dict = {}
        dict['id'] = item.id
        dict['hostname'] = item.hostname
        dict['hostaddr'] = item.hostaddr
        dict['hostmode'] = item.hostmode
        list.append(dict)

    pageInator = Paginator(list,pageSize)
    context = pageInator.page(pageIndex)
    for item in context:
        res.append(item)
    data = { "code": 0,"msg": "ok","DataCount": dataCount,"data": res }
    return HttpResponse(json.dumps(data))

def search_page(request):
    sql = request.GET.get("hostname")
    data = models.HostDB.objects.all().filter(hostname=sql)
    list = []

    for item in data:
        dict = {}
        dict['id'] = item.id
        dict['hostname'] = item.hostname
        dict['hostaddr'] = item.hostaddr
        dict['hostmode'] = item.hostmode
        list.append(dict)

    data = { "code": 0,"msg": "ok","DataCount": 1,"data": list }
    return HttpResponse(json.dumps(data))

def delete_page(request):
    get_id = request.GET.get("id")
    models.HostDB.objects.filter(id=get_id).delete()
    return render(request,"index.html")

def update_page(request):
    get_id = request.GET.get("id")
    get_hostname = request.GET.get("hostname")
    get_hostaddr = request.GET.get("hostaddr")
    get_hostmode = request.GET.get("hostmode")

    print(get_hostmode)
    obj = models.HostDB.objects.get(id=get_id)
    obj.hostname = get_hostname
    obj.hostaddr = get_hostaddr
    obj.hostmode = get_hostmode
    obj.save()
    return render(request,"index.html")

路由层增加修改接口,方便调用。

# name: url.py
from django.contrib import admin
from django.urls import path
from MyWeb import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.index),
    path('get_page/',views.get_page),
    path('search_page/',views.search_page),
    path('delete_page/',views.delete_page),
    path("update_page/",views.update_page)
]

img