I've been stuck with this problem for a few days now. I'm trying to feed JSON data to DataTables, but it only works if I use static file as source (see below index.html).
index.html
$(document).ready(function() {
$('#mydata').DataTable( {
"ajax": {
"url": '{% static "myapp/supplier.json" %}', //<= works
{# "url": '{{ suppliers_all }}',#} //<=does not work
"dataSrc": ""
},
"columns": [
{ "data": "name" },
{ "data": "classification" },
]
} );
} );
views.py
def index(request):
suppliers_all = Supplier.objects.all().values('name', 'classification')
suppliers_all = json.dumps(list(suppliers_all))
context = {'suppliers_all': suppliers_all,
}
return render(request, 'myapp/index.html', context)
JSON output:
[{"classification": "Base Supplier", "name": "Supplier Name1"}, {"classification": "Strategic Supplier", "name": "Supplier Name2"}]
When I use django passed variable {{ suppliers_all }}
browser debugging returns a 404 not found error. I tried hardcoding JSON output according to websites examples, tried many different ways, but it will never work if it's not fetched directly from file.
Update: Solved problem by creating new view with JSON Httpresponse and url
def supjson(request):
suppliers_all = Supplier.objects.all().values('name', 'classification')
suppliers_all = json.dumps(list(suppliers_all), cls=DjangoJSONEncoder)
context = {'suppliers_all': suppliers_all,
return HttpResponse(suppliers_all, content_type='application/json')
Then changed Ajax url to the following:
"ajax": {
"url": '{% url 'myapp:supjson' %}',
"dataSrc": ""
},
While it works, I feel it's redundant solution as I have issues passing data through the variable directly.
Update #2: Issue was due to Django autoescaping single commas which then made JSON parsing did not work. I did the following changes:
Added mark_safe in the views.py
context = {'suppliers_all': mark_safe(suppliers_all),
}
Stringified JSON and then Parsed it in index.html template:
$(document).ready(function() {
var json=JSON.stringify({{ suppliers_all }});
$('#mydata').DataTable( {
"data": JSON.parse(json),