1

I'm a new Django user, stuck on a problem. I'd like to obtain an auto-refresh of my jQuery Datatables datas, showing my new DB content without reload entire html page (using ajax request). I browsed a lot of posts, but did not find my graal...

Here is my Django template.html :

{% block js %} 
<script type="text/javascript" language="javascript" class="init">
  $(document).ready(function(){
  var oTable = $('#db_name').DataTable();
  } );

  setInterval(function () {
      oTable.ajax.reload();
  }, 2000 );
} );

</script> 
{% endblock %}

My views.py :

def db_update(request):
    watch_files()
    all_ = db.objects.all()
    return render_to_response('supervision.html', {'all_fields': all_})

The problem is an error message "Datatables warning: table id=db_name - Invalid JSON response" displayed each 2sec. I think this is normal because no JSON. Despite this error, the reload is effective : if I do a manual refresh (F5), all new datas added in my DB (the function watch_files create entries in it) appear well in my page. The ideal, for me, would be to obtain a transparent datas auto-refresh, keeping current sort/page options of the Datatables array.

I tried also this, trying to pass JSON, but without success :

$(document).ready(function() {
  var oTable = $('#db_name').DataTable( {
      ajax: {{obj_as_json}}
  } ); 

  setInterval(function () {
      /* oTable.ajax.reload(); */
      oTable.fnReloadAjax();
      /* oTable.fnDraw(); */
  }, 2000 );
} );

def db_update(request):
    watch_files()
    all_ = db.objects.all()
    jsondata = serializers.serialize('json', all_)
    return render_to_response('supervision.html', {
        'obj_as_json':json.dumps(jsondata), 
        'all_fields': all_})

If anybody could help me, it would be great. Thks, Christophe

liblib
  • 19
  • 3
  • possible duplicate of [Creating a JSON response using Django and Python](http://stackoverflow.com/questions/2428092/creating-a-json-response-using-django-and-python) – madzohan Jul 10 '15 at 13:22

1 Answers1

0

render_to_response('supervision.html') always return an html content that produced by supervision.html template.

You need to return JsonResponse object, that would contain json data only.

from django.http import JsonResponse
def db_update(request):
    watch_files()
    all_ = db.objects.all()
    if request.is_ajax():
        jsondata = serializers.serialize('json', all_)
        return JsonResponse(jsondata)
    else:
        return render_to_response('supervision.html', {
            'all_fields': all_})

In addition, you need to transform your all_ variable to looks like datatables expects

{
   "data": [
      [ "column1_val",
        "column2_val",
         ...
      ],
    ]
}

I suggest you take a look to https://github.com/pivotal-energy-solutions/django-datatable-view implementation

kmmbvnr
  • 5,863
  • 4
  • 35
  • 44