I am new developer and this is my first professional project and first in Django too.
I am trying to load data I fetched from my models.py in my view.py to a DataTable.
Here is my code.
Here is my views.py
def recordingDataTable(request):
if request.is_ajax and request.method == "GET":
vicidial_agent_log = VicidialAgentLog.objects.filter(event_time__gte='2021-04-16 16:00:00').values('user', 'server_ip')
structure = json.dumps(list(vicidial_agent_log), cls=DjangoJSONEncoder)
return JsonResponse(structure, status = 200, safe=False)
return JsonResponse({}, status = 400)
Here is the JSON that gets returned
"[{\"user\": \"8045\", \"server_ip\": \"168.119.48.158\"}, {\"user\": \"8047\", \"server_ip\": \"168.119.48.158\"},]"
Here is my Template
<table id="recording_datatable" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>Username</th>
<th>Server IP</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<th>Username</th>
<th>Server IP</th>
</tr>
</tfoot>
</table>
Finally, here is my script
$(document).ready(function() {
$.ajax({
'url': "{% url 'recordings:recordingDataTable' %}",
'method': "GET",
'dataType': "JSON",
'contentType': 'application/json',
}).done( function(data) {
alert(data);
$('#recording_datatable').DataTable({
data: data,
dataSrc: "",
columns: [
{ data: "user" },
{ data: "server_ip" },
]
});
})
});
Whenever I run my code, I receive the following error:
DataTables warning: table id=recording_datatable - Requested unknown parameter 'user' for row 0, column 0. For more information about this error.
I have implemented a DataTable before already from PHP and seem to be doing everything right. I just don't know why it isn't working. I have visited almost every document on here, Stackoverflow and Datatables.net and for some reason no implementation seem to be working.
I know it will turn out to be a simple error but this problem has taken better part of my 3 days. Any help will be very appreciated. Thank you.
json.dumps? You should be passing an array of objects to JsonResponse,[ {"user": "Joe" }, { "user": "Jane" } ]- not passing a string.const parsedData = JSON.parse(data);. I used json.dumps() because of a solution I found online. I guess my Python or web development needs to be sharpen a lot. Thanks man for your help. Lastly, can you help me why myreturn JsonResponse(structure, status = 200, safe=False)is not returning JSON to my template?