从Django检索数据通过Datatable选择Option

问题描述 投票:0回答:1

我有一个问题,我无法在渲染数据表或触发后调用 Django 数据,该数据是

payrolled_list
到选择选项中。我只是希望 Django 中的数据反映到选择选项,但我使用 Datatable 来触发,然后反映任何人都可以对我的问题有想法,我非常感激!

我尝试填充数据来选择,但不知道如何调用它,有必要使用“{{payrolled_list}}”,因为它是 django 并反映到 select2 ?

 drawCallback: function (settings) {
    let myDataTable = $('#tbl-box-a').DataTable();
    let payrolledListData = [];
    $('#payroll-name').empty();

    // Add an empty option
    $('#payroll-name').append('<option></option>');

    // Populate options based on payrolled_list data
    for (let i = 0; i < payrolledListData.length; i++) {
        $('#payroll-name').append('<option value="' + payrolledListData[i].id + '">' + payrolledListData[i].name + '</option>');
    }

}

html 选择

<select id="payroll-name" name="PayrollName" class="form-select employee" data-allow-clear="true" ><option></option></select>

姜戈

payrolled_list = serialize('json', TevIncoming.objects.filter(status_id=4).order_by('first_name'))

response = {
    'data': data, //data is list
    'payrolled_list': payrolled_list  //this data I want to populate it to select option
}
return JsonResponse(response)

这是我的整个代码数据表

    const table2 = $('#tbl-box-a');

    if ($.fn.DataTable.isDataTable('#tbl-box-a')) {
    table2.DataTable().destroy();
    }

    dataTable2 = table2.DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: "{% url 'employee-dv' %}",
            data: function (d) {
                d.dv_id = dv_no_id;
            },
        },
        columns: [
            { data: 'id' },
            { data: 'code' },
            { data: 'account_no' },
            { data: 'id_no' },
            { data: 'name' },
            { data: 'final_amount' },
            { data: 'purpose' },
            { data: 'dv_no', name: 'dv_no' },
            { data: 'multiple_charges' },
            { data: 'total', name: 'total' },
        ],
    
        columnDefs: [
             {   
                targets: 0,
                render: function(data, type, row, meta) {
                   
                    // Set the data-row-id attribute on the <tr> element
                    return '<tr data-row-id="' + row.id + '"><td><input type="checkbox"></td></tr>';
                },
            },
            {
                targets: 1,
                render: function(data) {
                    return data
                },
            },
            {
                targets: 2,
                render: function(data) {
                    console.log(data);
                    return (!data && data !== 0) ? '' : '<span class="badge bg-label-warning">' + data + '</span>';
                },
            },
            {
                targets: 3,
                render: function(data) {
                    return '<span class="badge bg-label-primary">' + data + '<span>'
                },
            },

            
            {
                targets: 5,
                render: function (data) {
                    return data

                },
            },
            {
                targets: 6,
                render: function (data) {
                    
                    return '<td><input type="text" class="form-control emp-purpose" value="'+data+'"></td>'

                },
            },
            {
                targets: 7,
                render: function (data) {
                    let charges =  '<select class="form-select emp-charges" id="emp-charges">' +
                    '<option></option>'+
                    '{% for row in charges %}'+
                    '<option value="{{ row.id }}">{{ row.name }}</option>'+
                    '{% endfor %}'+
                    '</select>';
                    return charges
                },
            },
            {
                targets: -1,
                title: 'Action',
                orderable: false,
                searchable: false,
                render: function (data) {
                    var itemId = data;
                    return '<a class="btn btn-sm btn-icon item-delete" id="${item.id}" ><i class="text-primary ti ti-trash"></i></a>';
                },
            },
            
        ],
        dom: '<"card-header flex-column flex-md-row"<"head-label text-center"><"dt-action-buttons text-end pt-3 pt-md-0"B>><"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6 d-flex justify-content-center justify-content-md-end"f>>t<"row"<"col-sm-12 col-md-6"i><"col-sm-12 col-md-6"p>>',
        buttons: [],
        drawCallback: function (settings) {
            let myDataTable = $('#tbl-box-a').DataTable();
            let payrolledListData = [];
            $('#payroll-name').empty();
        
            // Add an empty option
            $('#payroll-name').append('<option></option>');
        
            // Populate options based on payrolled_list data
            for (let i = 0; i < payrolledListData.length; i++) {
                $('#payroll-name').append('<option value="' + payrolledListData[i].id + '">' + payrolledListData[i].name + '</option>');
            }
        
            // Initialize Select2
            if ($('#payroll-name').length) {
                $('#payroll-name').wrap('<div class="position-relative"></div>');
                $('#payroll-name').select2({
                    placeholder: 'Choose Employee',
                    dropdownParent: $('#payroll-name').parent(),
                    allowClear: true,
                });
            }
        }
    });
}
javascript html jquery django
1个回答
0
投票

一种方法是使用 dataSrc 选项。当服务器返回响应时,您可以使用回调函数并获取所需的数据进行操作。

下面是执行此操作的快速示例。我只是出于演示目的更改了网址和数据,但在您的情况下,您只需在传递给函数并返回实际数据时将 data 更改为 data.payrolled_list

const table2 = $('#tbl-box-a');

if ($.fn.DataTable.isDataTable('#tbl-box-a')) {
  table2.DataTable().destroy();
}

dataTable2 = table2.DataTable({
  processing: true,
  serverSide: true,
  ajax: {
    url: "https://jsonplaceholder.typicode.com/posts/1/comments",
    dataSrc: function(data) {
      addOptionstoDropdown(data) //data.payrolled_list
      return data //data.data
    },
  },
  columns: [{
      data: 'id'
    },
    {
      data: 'name'
    },
    {
      data: 'email'
    }
  ],

  columnDefs: [{
      targets: 0,
      render: function(data, type, row, meta) {

        // Set the data-row-id attribute on the <tr> element
        return '<tr data-row-id="' + row.id + '"><td><input type="checkbox"></td></tr>';
      },
    },
    {
      targets: 1,
      render: function(data) {
        return data
      },
    },
    {
      targets: 2,
      render: function(data) {
        return (!data && data !== 0) ? '' : '<span class="badge bg-label-warning">' + data + '</span>';
      },
    },
  ],
  dom: '<"card-header flex-column flex-md-row"<"head-label text-center"><"dt-action-buttons text-end pt-3 pt-md-0"B>><"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6 d-flex justify-content-center justify-content-md-end"f>>t<"row"<"col-sm-12 col-md-6"i><"col-sm-12 col-md-6"p>>',
  buttons: [],

});

function addOptionstoDropdown(payrolledListData) {
  $('#payroll-name').empty();

  // Add an empty option
  $('#payroll-name').append('<option></option>');
  // Populate options based on payrolled_list data
  for (let i = 0; i < payrolledListData.length; i++) {
    $('#payroll-name').append('<option value="' + payrolledListData[i].id + '">' + payrolledListData[i].name + '</option>');
  }

  // Initialize Select2
  if ($('#payroll-name').length) {
    $('#payroll-name').wrap('<div class="position-relative"></div>');
    $('#payroll-name').select2({
      placeholder: 'Choose Employee',
      dropdownParent: $('#payroll-name').parent(),
      allowClear: true,
    });
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.datatables.net/1.10.24/css/jquery.dataTables.min.css" rel="stylesheet" type="text/css" />
<script src="https://cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>

<select id="payroll-name" style='width:200px'></select>
<table class="table table-bordered table-hover GCSA3011 ptbl dataTable no-footer dtr-inline" id="tbl-box-a" role="grid">
  <thead>
    <tr>
      <th>Id</th>
      <th>Name</th>
      <th>Email</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

© www.soinside.com 2019 - 2024. All rights reserved.