Javascript Django使用ChartJS显示图形
我需要用我的费用做一个图表 这是我的看法Javascript Django使用ChartJS显示图形,javascript,django,chart.js,Javascript,Django,Chart.js,我需要用我的费用做一个图表 这是我的看法 @login_required def index(request): truncate_month = connection.ops.date_trunc_sql('month', 'date_reg') expense = Expense.objects.extra({'month': truncate_month}).values('month').annotate(Sum('total_amount')) return r
@login_required
def index(request):
truncate_month = connection.ops.date_trunc_sql('month', 'date_reg')
expense = Expense.objects.extra({'month': truncate_month}).values('month').annotate(Sum('total_amount'))
return render(request, 'home/index.html', {"expense": expense})
在我的模板上
{{ expense }}
并以以下格式显示数据:
[{
'month': '2015-12-01',
'total_amount__sum': 900.0
}, {
'month': '2016-01-01',
'total_amount__sum': 19334.0
}]
如何格式化该数据以与chartjs兼容
ChartJs示例:
labels: ["January", "February", "March", "April", "May", "June", "July"], //Here the month
datasets: [{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [65, 59, 80, 81, 56, 55, 40] //here 'total_amount__sum'
},
...
看一看价值清单: 这将为您提供值列表,而不是字典。一种方法是连接: 在模板中:
data = JSON.parse({{ expense|safe }});
var labels = _.pluck(data, 'month');
var data = _.pluck(data, 'total_amount__sum');
正如bryanph所说,使用Values_list,然后要更改ASCII的引号,需要在模板中转义它们。你可以使用安全过滤器 视图中的行: 费用=费用。价值清单(“月”,单位=真) 模板:
{{ expense|safe }}
谢谢布莱恩夫,我照你的建议做了。在我看来:expenses=expense.values_list('month',flat=True),现在浏览器显示['2015-12-01','2016-01-01'],这太棒了。但图表不起作用,因为引用是在Ascci(')中打印的:标签:[(';2015-12-01';),(';2016-01-01';)],我如何防止这种行为?这并没有提供问题的答案。一旦你有足够的钱,你将能够;相反嗨,史蒂夫,我编辑了这篇文章,对不起,这是我第一次真正回答堆栈溢出问题。我也有同样的问题,布莱恩夫的回答和卡洛斯的评论帮助我找到了完整的解决方案。
{{ expense|safe }}