1👍
For a dict
or list
, best to use JSON, because that renders a Javascript data structure (the JS in JSON refers to Javascript)
import json
return render(request, 'home.html', {
'labels': json.dumps(labels),
'data': json.dumps(data)
})
Then in the Django template, the output of the json.dumps()
call is a valid JS object.
var labels = {{labels}};
var data = {{data}};
0👍
You’ll need to render your data as if it were a string so that the output is valid javascript that the browser can interpret:
var data = {{ str(data) }};
var labels = {{ str(labels) }};
The above expressions convert the array into a string representation of the array, so [1, 2, 3]
would be rendered as '[1,2,3]'
and ["a", "b", "c"]
would be rendered as '["a","b","c"]'
.
A quick way to check if this is working right would be to right click and view the page source, then scroll down to this javascript and verify that it looks like valid variable declarations. If it doesn’t seem to be working, edit your question with the rendered javascript you see while inspecting the page source.
0👍
I have found the most reliable way to render any data, is to use the safe
django template filter, so it doesn’t try and encode any special fields.
return render(request,
'home.html',
{'labels': json.dumps(labels),'data': json.dumps(data)}
)
Then render using using the safe
template filter. This
<script>
var labels = {{labels | safe}};
var data = {{data | safe}};
...
</script>