layui制作数据表格

显示效果

layui制作数据表格

前端代码

{% extends "base.html" %}
{% block content %}
<div class="layui-card">
    <table id="demo" lay-filter="test"></table>
    <script type="text/html" id="toolbarDemo">
        <input type="text" name="user" class="layui-input" style="width: 150px; float: left">
        <button class="layui-btn" style="float: left" id="searchBtn">搜索</button>
{#        <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>#}
        <div class="layui-input-inline">
            <select name="sex" lay-verify="required" lay-search="" lay-filter="sex">
                <option value="">直接选择或输入性别</option> <option value="男">男</option> <option value="女">女</option>
            </select>
        </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>
</div>
<button type="submit" class="layui-btn" id="registerBtn">注册用户</button>
{% endblock %}

{% block js %}
<script>
layui.use(['layer','table','form'], function(){
    var table = layui.table;
    var layer = layui.layer;
    var $ = layui.jquery;
    var form = layui.form;

    $("#registerBtn").click(function () {
        // 加载层
        layer.open({
            type: 2,
            content: "{% url 'register_user' %}",
            area: ['50%','80%'],
            title: ['注册用户', 'font-size:28px;'],
            btn: ['提交','关闭']
        })
    });

  table.render({
    elem: '#demo'  // 元素ID
    ,url: "{% url 'list_user' %}"
    ,toolbar: '#toolbarDemo' //开启头部工具栏,并为其绑定左侧模板
    ,defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义,去除该参数即可
      title: '提示'
      ,layEvent: 'LAYTABLE_TIPS'
      ,icon: 'layui-icon-tips'
    }]
    ,title: '用户数据表'
    ,cols: [[
        {type: 'checkbox', fixed: 'left'}
      ,{field:'user', title:'用户名', width:120,}
      ,{field:'name', title:'名字', width:120, }
      ,{field:'sex', title:'性别', width:120,templet: function (d) {
                if (d.sex == "女") {
                    return '<span style="color: red">' + d.sex + '</span>'
                } else {
                    return '<span style="color: blue">' + d.sex + '</span>'
                }
              }}
      ,{field:'age', title:'年龄', width:120,}
      ,{field:'role', title:'角色', width:120,}
      ,{field:'label', title:'标签', width:120,}
      ,{fixed: 'right', title:'操作', toolbar: '#barDemo', width:150}
    ]]
      ,page: true
      ,id: "user_table"     //用于表格重载
  });

  //头工具栏事件
  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;
    if(obj.event === 'del'){
      layer.confirm('真的删除行么', function(index){
        csrfmiddlewaretoken = $('input[name=csrfmiddlewaretoken]').val();
        var post_data = {'user':data.user, 'csrfmiddlewaretoken':csrfmiddlewaretoken}
        $.ajax({
            type: "POST",
            url: "{% url 'list_user' %}",
            data: post_data,
            success: function (result) {
                if (result.code == "0") {
                    layer.msg(result.msg, {icon: 6})
                } else {
                    layer.msg(result.msg, {icon: 5})
                }
            }
        })
      });
    } else if(obj.event === 'edit'){
      layer.prompt({
        formType: 2
        ,value: data.email
      }, function(value, index){
        obj.update({
          email: value
        });
        layer.close(index);
      });
    }
  });

  $(document).on('click', "#searchBtn",function () {    //解决第二次搜索失效的问题
  // $("#searchBtn").click(function () {
      var search_var = $('input[name=user]').val();
      table.reload('user_table', {
          where: { //设定异步数据接口的额外参数,任意设
            searchKey: search_var
          }
          ,page: {
            curr: 1 //重新从第 1 页开始
          }
        }); //只重载数据
  })

    form.on('select(sex)', function(data){
      {#console.log(data);#}
      table.reload('user_table', {
          where: { //设定异步数据接口的额外参数,任意设
            sexKey: data.value,
          }
          ,page: {
            curr: 1 //重新从第 1 页开始
          }
        }); //只重载数据
    });
});
</script>

{% endblock %}

后端代码

# 用户管理
@self_login_required
def manage_users(request):
    return render(request,"manage_users.html")

# 注册用户
@self_login_required
def register_user(request):
    if request.method == "GET":
        return render(request, "register_user.html")
    elif request.method == "POST":
        # 从数据库获取所有用户名
        user_list = []  # 用户名列表
        for users in User.objects.all():
            user_list.append(users.user)

        # 判断数据库是否有该用户
        user = request.POST.get("user", None)
        if user in user_list:
            code = 1
            msg = f"{user}用户已存在"
            result = {"code": code, "msg": msg}
            return JsonResponse(result)
        password = request.POST.get("password", None)
        name = request.POST.get("name", None)
        sex = request.POST.get("sex", None)
        age = request.POST.get("age", None)
        role = request.POST.get("role", None)
        label = request.POST.get("label", None)
        try:
            User.objects.create(
                user=user,password=password,name=name,sex=sex,age=age,role=role,label=label
            )
            code = 0
            msg = f"{user}用户注册成功"
        except Exception as e:
            print(e)
            code = 1
            msg = "注册失败"
        result = {"code":code, "msg": msg}
        return JsonResponse(result)

# 查看用户
@self_login_required
def list_user(request):
    user_list = []  # 用户名列表
    user_dt = {}    # 单个用户信息字典
    data = []       # 存放所有用户的信息
    if request.method == "GET":
        try:
            for users in User.objects.all():
                user_list.append(users.user)
            for username in user_list:
                user_info = User.objects.get(user='%s' % username)
                user_dt["user"] = user_info.user
                user_dt["name"] = user_info.name
                user_dt["sex"] = user_info.sex
                user_dt["age"] = user_info.age
                user_dt["role"] = user_info.role
                user_dt["label"] = user_info.label
                # 根据查询关键字返回数据
                search_key = request.GET.get('searchKey',None)
                sex_key = request.GET.get('sexKey',None)
                if search_key or sex_key:
                    if search_key in user_info.user:
                        data.append(user_dt)
                    if sex_key == user_info.sex:
                        data.append(user_dt)
                else:
                    data.append(user_dt)
                user_dt = {}    # 清空
            # 分页
            count = len(data)
            page = int(request.GET.get('page',1))
            limit = int(request.GET.get('limit'))
            start = (page-1)*limit
            end = page*limit
            data = data[start:end]
            code = 0
            msg = "获取数据成功"
        except Exception as e:
            print(e)
            code = 1
            msg = "获取数据失败"
            count = 0
        result = {"code":code, "data":data, "msg":msg, "count": count}
        return JsonResponse(result)
    elif request.method == "POST":
        user = request.POST.get('user',None)
        try:
            if user:
                User.objects.filter(user=user).delete()
                code = 0
                msg = "用户刪除成功"
        except Exception as e:
            print(e)
            code = 0
            msg = "用户删除失败"
        result = {"code": code,"msg": msg}
        return JsonResponse(result)
上一篇:关于props配置项


下一篇:【Thymeleaf】[[]]和[()]