美文网首页Python自动化运维
django 使用datatables的服务器模式

django 使用datatables的服务器模式

作者: Blues_rat | 来源:发表于2018-05-10 10:36 被阅读69次

    需要在url中配置路由,/work/list/指向到work_list

    JS代码:

     $(document).ready(function() {
    
        $("#dataTables-example").dataTable(
            {
                // 开启服务器模式
                "serverSide": true,
                // 开启处理功能
                "processing" : true,
                // 允许排序
                "orderable":true,
                // 允许查询
                "searching" : true,
                 // 根据第四列降序排列
                "order": [[ 3, "desc" ]],
                // 发送post请求
                "ajax":{
                    "type": 'POST' ,
                    "url": '/work/list/'
                },
                // 返回数据
                columns: [
                    { "data": "name",
                        // 数据渲染,返回超链接的字条
                        "render": function ( data, type, full, meta ) {
                            return '<a href="/work/work_results?name='+data+'" ><span>'+data+'</span></a>';
                    }
                    },
                    { "data": "user" },
                    { "data": "fun" },
                    { "data": "start_time" },
                    { "data": "end_time" },
                    { "data": "sum_time" },
                    { "data": "status",
                        // 数据渲染,判断返回内容,返回span颜色
                        "render": function (data, type, full, meta) {
                            if (data == '执行成功') {
                                return '<span class="label label-success">' + data + '</span>';
                            }
                            else if (data == '执行失败') {
                                return '<span class="label label-danger">' + data + '</span>';
                            }
                            else if (data == '执行中') {
                                return '<span class="label label-warning">' + data + '</span>';
                            }
                            else {
                                return '<span class="label label-primary">' + data + '</span>';
                            }
                        }}
                ],
                'columnDefs': [{
                    'targets': 0,
                    'searchable': true
            }]
    
            }
    
        );
    });
    
        
      $("form").submit(function(e){
        e.preventDefault();
        table = $("#dataTables-example").DataTable();
        table.ajax.reload();
    });
    

    国际化

    $(function() {
        var oLanguage = {
            "oAria": {
                "sSortAscending": ": 升序排列",
                "sSortDescending": ": 降序排列"
            },
            "oPaginate": {
                "sFirst": "首页",
                "sLast": "末页",
                "sNext": "下页",
                "sPrevious": "上页"
            },
            "sEmptyTable": "没有相关记录",
            "sInfo": "第 _START_ 到 _END_ 条记录,共 _TOTAL_ 条",
            "sInfoEmpty": "第 0 到 0 条记录,共 0 条",
            "sInfoFiltered": "(从 _MAX_ 条记录中检索)",
            "sInfoPostFix": "",
            "sDecimal": "",
            "sThousands": ",",
            "sLengthMenu": "每页显示条数: _MENU_",
            "sLoadingRecords": "正在载入...",
            "sProcessing": "正在载入...",
            "sSearch": "",
            "sSearchPlaceholder": "",
            "sUrl": "",
            "sZeroRecords": "没有相关记录"
        }
        $.fn.dataTable.defaults.oLanguage = oLanguage;
    });
    

    table表代码

    <table class="table table-striped table-hover" id="dataTables-example">
        <colgroup>
            <col style="width:8%">
            <col style="width:4%;">
            <col style="width:2%;">
            <col style="width:6%;">
            <col style="width:4%;">
            <col style="width:4%;">
            <col style="width:4%;">
        </colgroup>
        <thead>
            <tr>
                <th>作业名称</th>
                <th>执行人</th>
                <th>执行方式</th>
                <th>开始时间</th>
                <th>结束时间</th>
                <th>总耗时</th>
                <th>作业状态</th>
            </tr>
       </thead>
       <tbody>
       </tbody>
    </table>
    

    后端代码:

    def work_list(request):
        from django.db.models import Q
        if request.method == "POST":
            # 获取所有数据
        all_result = running_list.objects.all().order_by("-start_time")
            # 数据条数
        recordsTotal = all_result.count()
        recordsFiltered = recordsTotal
            # 第一条数据的起始位置
        start = int(request.POST['start'])
            # 每页显示的长度,默认为10
        length = int(request.POST['length'])
            # 计数器,确保ajax从服务器返回是对应的
        draw = int(request.POST['draw'])
            # 全局收索条件
        new_search = request.POST['search[value]']
            # 排序列的序号
        new_order= request.POST['order[0][column]']
            # 排序列名
        by_name = request.POST['columns[{0}][data]'.format(new_order)]
            # 排序类型,升序降序
        fun_order = request.POST['order[0][dir]']
            # 排序开启,匹配表格列
        if by_name:
                if fun_order == "asc":
                    all_result = all_result.order_by(by_name)
                else:
                    all_result = all_result.order_by("-{0}".format(by_name))
            # 模糊查询,包含内容就查询
        if new_search:                
            all_result = all_result.filter(Q(user__contains= new_search) | Q(fun__contains=new_search) |
                       Q(start_time__contains=new_search) | Q(end_time__contains=new_search) |
                       Q(sum_time__contains=new_search) | Q(status__contains=new_search))
            # 获取首页的数据
        datas = all_result[start:(start+length)]
            # 转为字典
        resp = [obj.as_dict() for obj in datas]
    
            #返回计数,总条数,返回数据
        result = {
            'draw': draw,
            'recordsTotal': recordsTotal,
            'recordsFiltered': recordsFiltered,
            'data': resp,
            }
       return HttpResponse(json.dumps(result), content_type="application/json")

    相关文章

      网友评论

        本文标题:django 使用datatables的服务器模式

        本文链接:https://www.haomeiwen.com/subject/zdxzrftx.html