Reputation: 39
I am trying to create a chart Using Chartjs and Django, i have a problem when i am trying to pass the data from views.py to js code.
so,this is my code in views.py..
def home(request):
labels = ["A", "B", "C", "D"]
data = [1,2,3,4]
return render(request, 'home.html',{'labels': labels
,'data': data,})
and this is my part of code in home.html ..
<script>
var labels = {{labels}};
var data = {{data}};
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
labels: labels,
datasets: [{
label:"chartLabel",
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data:data,
}]
},
// Configuration options go here
options: {}
});
</script>
put when i use these tow lines in js ..
var labels = ["A", "B", "C", "D"];
var data = [1,2,3,4];
instead of this tow my code works fine.
var labels = {{labels}};
var data = {{data}};
Upvotes: 0
Views: 1644
Reputation: 26
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>
Upvotes: 0
Reputation: 12548
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}};
Upvotes: 1
Reputation: 20076
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.
Upvotes: 0