Ajax works reading JSON datasource from file, but not from variable (Django)
Ajax works reading JSON datasource from file, but not from variable (Django)
termis
Posts: 5Questions: 2Answers: 1
I really hope someone will help with the problem I've been stuck. I have a below code in my 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" },
]
} );
} );
If I have source to "supplier.json" file it works like a charm, but if I try to pass django variable which gives exactly same out, it does not work.
Here's the "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)
Here is JSON output"
[{"classification": "Base Supplier", "name": "Supplier Name1"}, {"classification": "Strategic Supplier", "name": "Supplier Name2"}]
Any ideas?
thanks
This question has an accepted answers - jump to answer
This discussion has been closed.
Answers
Not sure about the code but I think the JSON should look like this:
{data: [{"classification": "Base Supplier", "name": "Supplier Name1"}, {"classification": "Strategic Supplier", "name": "Supplier Name2"}]}
Kevin
It's still a valid JSON, but even if I hardcode JSON output from this site, I still get the same error
What is the error you get?
I'm not familiar with Django but I use a Python with Cherrypy backend for my project. It looks like you are having Django load the page with the data set ready to display. My procedure is different. Cherrypy loads the page (index), the client then sends the AJAX request to ```get_data`` which is a Python function get the data and return the JSON object.
Here is an example of my Python/Cherrypy code.
The above function returns the web page which includes the following Datatable:
The
get_data
(edited for brevity) function performs the SQL query and returns a JSON objectdata
that has an array of objects containing the data:result
is a dictionary list of returned items from the SQL query. The returned JSON object looks like this:{data: [{pkid: 1, name: "name1}, {pkid: 2, name: "name2"}]}
You can look at this example to see the required structure of the JSON object:
https://datatables.net/examples/data_sources/ajax.html
Kevin
I finally understood what was wrong. Issue was that Django auto escaped single commas in JSON string so I couldn't parse it. I solved the following way by stringifying JSON and adding "| safe":
Nice one - thanks for posting back!
Allan