我正在尝试使用Django(使用Mac Maverick)创建带有高图的饼图,但我只是得到一个空白页面。我的代码下面是否有错误? 我的数据包含一个带有2个键的字典(body和id__count),它内部的循环在body标签中完美运行。但是它没有在脚本标签中工作。
<script>
function numberWithCommas(x) {
var parts = x.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return parts.join(".");
}
$(function () {
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'categoryPieChart'
},title: {
text: 'Category'
},tooltip: {
formatter: function() {
return '<b>'+ this.point.name +'</b>: '+ numberWithCommas(this.y.toFixed(2));
}
},exporting: {
enabled: false
},plotOptions: {
pie: {
dataLabels: {
enabled: true,
formatter: function() {
return '<b>'+ this.point.name +'</b>: '+ Math.round(this.percentage) +' %';
}
}
}
},series: [{
type: 'pie',
data: [
{% for cat in responses_pie %}
[
'{{ cat.body }}',
{% if cat.id__count > 0 %}
{{ cat.id__count }}
{% else %}
0
{% endif %}
],
{% endfor %}
]
}]
});
});
});
});
</script>
这是脚本代码中Chrome上的视图来源:
function numberWithCommas(x) {
var parts = x.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return parts.join(".");
}
$(function () {
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'categoryPieChart'
},title: {
text: 'Category'
},tooltip: {
formatter: function() {
return '<b>'+ this.point.name +'</b>: '+ numberWithCommas(this.y.toFixed(2));
}
},exporting: {
enabled: false
},plotOptions: {
pie: {
dataLabels: {
enabled: true,
formatter: function() {
return '<b>'+ this.point.name +'</b>: '+ Math.round(this.percentage) +' %';
}
}
}
},series: [{
type: 'pie',
data: [
[
'apple',
2
],
]
}]
});
});
});
});
我的观点(views.py)
def piechart(request):
responses_pie = AnswerRadio.objects.values("body").annotate(Count("id"))
return render(request, 'chart_code_v2.html', {'responses_pie': responses_pie})
答案 0 :(得分:1)
最后还有一个额外的});
(一个来自Highcharts.Chart({
,一个来自$(document).ready(function() {
,一个来自$(function () {
,另一个来自$(document).ready(fn)
。这应该是javascript控制台中的语法错误。
此外,调用$(fn)
是多余的,因为您在其周围的函数上使用的$(document).ready(fn)
是{% for cat in responses_pie %}
[
'{{ cat.body }}',
{% if cat.id__count > 0 %}
{{ cat.id__count }}
{% else %}
0
{% endif %}
]{% if not forloop.last %},{% endif %}
{% endfor %}
的简写。
如果您计划支持旧的Internet Explorer版本,则还需要从数据中删除最后一个逗号,例如:
json.dumps
通常,最好通过import json
def piechart(request):
responses_pie = AnswerRadio.objects.values("body").annotate(Count("id"))
res = []
for cat in responses_pie:
res.append([
cat.body,
cat.id__count,
# ... more stuff
])
return render(request, 'chart_code_v2.html', {'responses_pie_json': json.dumps(res)})
在视图中序列化数据并将字符串传递给模板,因为它不易出错。例如:
data: {{ responses_pie_json|safe }}
然后只需在模板中使用datetime
即可。请注意,某些Python对象(Decimal
,{{1}},...)需要一些额外的JSON序列化工作。