Is there an example showing how to use DataTables in conjunction with Django models?

Is there an example showing how to use DataTables in conjunction with Django models?

daneboy55daneboy55 Posts: 10Questions: 1Answers: 0
edited March 2019 in Free community support

I initialize datatable with this:

$(document).ready(function() {
    $('#mytable').DataTable( {
        "ajax":{
            "processing": true,
            "dataSrc": "",
            "url": "{% url 'Sensor_ajax_url' %}"
        }
    } );
} );

my view looks like this:

def Sensor_asJson(request):
    object_list = Sensor.objects.all()
    json = serializers.serialize('json', object_list)
    return HttpResponse(json, content_type='application/json;charset=utf-8')

It returns the single row in the data base:

[{"model": "sensors.sensor", "pk": 4, "fields": {"userid": 1, "update_date": "2019-03-09T19:15:58Z", "status": false, "name": "sidedoor", "zone": "firstfloor"}}]

Which does not work. What does "ajax.url" expect from the view?

This question has an accepted answers - jump to answer

Answers

  • colincolin Posts: 15,240Questions: 1Answers: 2,599

    Hi @daneboy55 ,

    I'm not familiar with Django, but if it's getting data returned, albeit just a single row, then I'd say the URL aspect is working fine and the problem would be in the view or the script that accesses the database.

    Hope that offers some help,

    Cheers,

    Colin

  • daneboy55daneboy55 Posts: 10Questions: 1Answers: 0

    Thanks for the response Colin. Yeah, it needs to be solved in the view. I have this code which works, but it's a cludge. I'd like to see a better way of doing this.

    My view now looks like this:

    def Sensor_asJson(request):
        object_list = Sensor.objects.all()
        serialized_objects  = serializers.serialize('json', object_list)
        json_objects=json.loads(serialized_objects)
        list_objects = []    
        for index in range(len(json_objects)):     
            list_objects.append(json_objects[index]['fields'])
        return HttpResponse(json.dumps(list_objects), content_type='application/json;charset=utf-8')
    

    My dataTables init look like this:

    $(document).ready(function() {
        
        $('#mytable').DataTable( {
    
            "ajax":{
                "processing": true,
                "dataSrc": "",
                "url": "{% url 'Sensor_ajax_url' %}"
            },
            "columns": [
                { "data": "userid"},
                { "data": "update_date"},
                { "data": "status"},
                { "data": "name"},
                { "data": "zone"}
            ]
            
        } );
    } );
    

    My url.py file is:

    urlpatterns = [
        path('show', views.show, name='show_template'),
        path('', views.Sensor_asJson, name='Sensor_ajax_url'),
    ]
    
  • kthorngrenkthorngren Posts: 21,341Questions: 26Answers: 4,954
    edited March 2019

    In your first post you have this json response:

    [{
        "model": "sensors.sensor",
        "pk": 4,
        "fields": {
            "userid": 1,
            "update_date": "2019-03-09T19:15:58Z",
            "status": false,
            "name": "sidedoor",
            "zone": "firstfloor"
        }
    }]
    

    With this structure you have nested objects which can be accessed like this example:
    https://datatables.net/examples/ajax/deep.html

    Your columns.data config will look like this:

            "columns": [
                { "data": "fields.userid"},
                { "data": "fields.update_date"},
                { "data": "fields.status"},
                { "data": "fields.name"},
                { "data": "fields.zone"}
            ]
    

    I'm not familiar with Django but it looks like you second version of Sensor_asJson is doing some extra work. Looks like line 3 (serialized_objects = serializers.serialize('json', object_list)) is creating a json string but then you are parsing the string back to a Python object in line 4. So I think object_list in line 2 and json_objects in line 4 are effectively the same.

    You might be able to re-write this code:

        list_objects = []   
        for index in range(len(json_objects)):    
            list_objects.append(json_objects[index]['fields'])
    

    As this using list comprehension:

    list_objects = [x['fields'] for x in d]
    

    This is a long way of saying your second version could look like this to eliminate the nested objects:

    def Sensor_asJson(request):
        object_list = Sensor.objects.all()
        list_objects = [x['fields'] for x in object_list]
        return HttpResponse(json.dumps(list_objects), content_type='application/json;charset=utf-8')
    

    Kevin

  • daneboy55daneboy55 Posts: 10Questions: 1Answers: 0

    Thanks for the response. I did try and convert the queryset response to a list object with list(object_list) and then tried to iterate over the list to grab the "fields" values. I kept getting "Sensor object is not subscriptable". I get the same error with the listcomp.

    [12/Mar/2019 16:02:52] "GET /tablesensors/show HTTP/1.1" 200 5534
    
    Internal Server Error: /tablesensors/
    Traceback (most recent call last):
      File "/home/ubuntu/django-apps/doorenv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
        response = get_response(request)
      File "/home/ubuntu/django-apps/doorenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
        response = self.process_exception_by_middleware(e, request)
      File "/home/ubuntu/django-apps/doorenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response
        response = wrapped_callback(request, *callback_args, **callback_kwargs)
      File "/home/ubuntu/django-apps/doorstatus/tablesensors/views.py", line 23, in Sensor_asJson
        list_objects = [x['fields'] for x in object_list]
      File "/home/ubuntu/django-apps/doorstatus/tablesensors/views.py", line 23, in <listcomp>
        list_objects = [x['fields'] for x in object_list]
    TypeError: 'Sensor' object is not subscriptable
    
  • kthorngrenkthorngren Posts: 21,341Questions: 26Answers: 4,954
    Answer ✓

    Its hard to say without knowing what the sensor object contains. You might need to loop through it they way you have originally:

        list_objects = []   
        for index in range(len(json_objects)):    
            list_objects.append(json_objects[index]['fields'])
    

    It sounds like you have an idea of what the data structure needs to be. You just need to get your Python code to create that structure Datatables supports. It will be hard for us to help with the Python side. But if you have questions please post them.

    Kevin

This discussion has been closed.