[Answer]-Django jquery datatable: Uncaught TypeError: Cannot read property 'length' of undefined

1👍

Check the doumentation for jQuery DataTables:
https://www.datatables.net/examples/ajax/objects.html

You need to supply you data in the following format:

[
    {
    "name":    "Tiger Nixon",
    "position":   "System Architect",
    "salary":    "$3,120",
    "start_date": "2011/04/25",
    "office":    "Edinburgh",
    "extn":    "5421"
    },
    {...}
]

You can iterate over datas in you views to build the objects, append them to an array and then send the Response via JsonResponse:

from django.http import JsonResponse

datas = Datas.objects.all()
arr = []
for data in datas:
    arr.append({
        'key1': data.key1,
        'key1': data.key1,
    })
return JsonResponse(arr, safe=True)

0👍

View;

datas= Datas.objects.all()
            dataArray = []
            for store in datas:
                dataArray.append({
                    'objectname':data.objectname
                })

return JsonResponse({'data':dataArray}, safe=True)

Js;

$('#id_dataTable').dataTable({
            "sAjaxSource": '/getData/',
            "aoColumns": [
                {'mData': 'objectname'}
            ],
            "aoColumnDefs": [
                {
                    "aTargets": [0],
                    "sTitle": "Object",
                    "sClass": "align-center"
                }
            ],
            "bProcessing": true,
            "sAjaxDataProp": "data",
            "bServerSide": true,
            "bPaginate": false
        });

Here is an answer..

👤kbrk

Leave a comment