I’m new at DataTables js, I need a solution for my problem. I have a Django app where I use DataTables with server-side processing, the table template is dynamic for all the models I have, I just pass the columns (a list of dicts with data
, name
and title
) within the context of the template, pretty straightforward…
def my_page_view(request):
columns = generate_datatables_columns("MyModel")
return render(
request,
"my_page.html",
{"columns": columns}
)
<script>
$(document).ready(function() {
var columns = [];
{% for col in columns %}
var jsObject = {
{% for key, value in col.items %}
"{{ key }}": "{{ value }}",
{% endfor %}
};
columns.push(jsObject);
{% endfor %}
var table = $('#my-table').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "/my/url",
"type": "GET",
},
"columns": columns,
});
});
</script>
<table id="my-table" class="display" width="100%">
<thead>
<tr>
{% for column in columns %}
<th id="dt_col_{{column.data}}">{{ column.name }}</th>
{% endfor %}
</tr>
</thead>
</table>
After that, I needed to make some changes on the columns, but depending on the data received, meaning I should be able to update my columns inside the DataTable definition after having the data. To make the idea clearer, the following code represents one of the attempts I tried, using ajax.dataSrc
prop:
var table = $('#my-table').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "/my/url",
"type": "GET",
"dataSrc": function (json) {
var data = json.data;
var newColumns = columns;
// make changes on data and newColumns variables with some conditions...
// here should update the datatable columns with the value of newColumns.
return data;
}
},
"columns": columns,
});
With this method I couldn’t find a way to update the columns, I tried also other ways like using drawCallback
, or custom ajax function, but I always end up with a dead-end.
I will be really grateful if someone helped me with that.