I have generated a variable data
in Django with the following format:
data = [['100',10],['90',9],['80',8]]
and I've passed it off to my template using render_to_response:
return render_to_response('template.html', {
'data': data,
},
context_instance=RequestContext(request))
In the template header I have placed a call to Google Charts to generate a line chart:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Number');
data.addColumn('number', 'Number/10');
data.addRows( {{ data }} );
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240, title: "Numbers"});
}
</script>
When I do this, nothing is displayed. If I strip the strings out of data
and try again, the chart appears, but obviously with no x-axis labels.
I have also tried adding the data using the arrayToDataTable function:
var data = google.visualization.arrayToDataTable([
['Number', 'Number/10'],
{% for datum in data %}
{{ datum }},
{% endfor %}],
false);
but this again fails to display any chart.
Any suggestions on how I can change one of the above, or try another approach to get the x-axis labels to appear?
You have to disable the autoescaping of your results. You can do so by adding the safe filter:
data.addRows( {{ data|safe }} );
or
{% autoescape off %}
[...]
{{ data }}
[...]
{% endautoescape %}
My advice is, if you can install additional packages, to use one of these wrappers:
http://code.google.com/p/google-chartwrapper/
https://github.com/jacobian/django-googlecharts/
I can't add more than two links yet but another one is located here: code.google.com/p/django-graphs/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With