[英]Displaying a Google Chart Using Django
I have generated a variable data
in Django with the following format: 我在Django中生成了一个可变data
,格式如下:
data = [['100',10],['90',9],['80',8]]
and I've passed it off to my template using render_to_response: 我使用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: 在模板标题中,我调用了Google Charts来生成折线图:
<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. 如果我从data
删除字符串并重试,则会显示图表,但显然没有x轴标签。
I have also tried adding the data using the arrayToDataTable function: 我也尝试使用arrayToDataTable函数添加数据:
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? 有关如何更改以上内容之一的任何建议,或尝试其他方法来显示x轴标签?
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/ http://code.google.com/p/google-chartwrapper/
https://github.com/jacobian/django-googlecharts/ 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/ 我无法添加两个以上的链接,但另一个链接位于此处:code.google.com/p/django-graphs/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.