【发布时间】:2021-08-11 03:03:00
【问题描述】:
我正在尝试显示商店中最畅销商品的图表。所以我需要从数据库中获取信息并进入 html。图表似乎没有加载。当我尝试静态数据(来自 Google 的示例)时,它工作正常。但是,我似乎无法使用动态数据来做到这一点。我将数组转换为 json 并在 html 中使用 |safe 进行转义。然而它仍然没有出现。如果有人有关于如何修复它的提示,请帮助!
下面是我的views.py,我在其中调用了包含图表脚本的html文件。
def charts(request):
data_arr = []
for item in Item.objects.all():
data_arr.append([item.ItemName, item.quantity_sold])
return render(request,'coffeeapp/charts.html',{'item':json.dumps(data_arr)})
这是我在 charts.html 文件中的代码
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script>
google.charts.load('current', { packages: ['corechart'] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
// Define the chart to be drawn.
var data = google.visualization.arrayToDataTable(
['Item', 'Quantity Sold'],
[{{item|safe}}]
);
// Instantiate and draw the chart.
var chart = new google.visualization.PieChart(document.getElementById('myPieChart'));
chart.draw(data, null);
}
</script>
<!--Div that will hold the pie chart-->
<div id="myPieChart"/>
编辑 1:{{item|safe}} 中的内容
我已经在views.py中打印出项目,结果如下:
[["Espresso", 0], ["Cappuccino", 2], ["Black Coffee", 0], ["Cafe Latte", 0], ["Mocha", 0], ["Iced Americano", 0]....
在浏览器/html 中,我添加了一个alert({{item|safe}}) 作为function drawChart() 下的第一行,它准确地显示了我所看到的项目。
部分结果如下
Espresso,0,Cappuccino,2,Black Coffee,0,Cafe Latte,0,Mocha,0,Iced Americano,0,Iced Caramel Macchiato,0,Cold Brew,0....
编辑 2 - 解决方案
在 Marco 的回答的帮助下,我能够解决这个问题。 Marco 有修复标签的答案,但数据行是手动输入的静态含义,而我想从数据库中获取它。 因此,我将自己的观点修改为这样。
def charts(request):
return render(request,'coffeeapp/charts.html',{'item':Item.objects.all()})
我的 html 是:
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script>
google.charts.load('current', { packages: ['corechart'] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
// Define the chart to be drawn.
var data = google.visualization.arrayToDataTable([
[{ label: 'Item', type: 'string' },
{ label: 'Quantity Sold', type: 'number' }],
{% for i in item %}
['{{ i.ItemName }}', {{ i.quantity_sold }}],
{% endfor %}
]);
var options = {
'title': 'MOST ORDERED DRINKS',
'width': 700,
'height': 700
};
// Instantiate and draw the chart.
var chart = new google.visualization.PieChart(document.getElementById('myPieChart'));
chart.draw(data, options);
}
</script>
我不确定它是如何工作的,但它没有安全关键字。
【问题讨论】:
标签: javascript python json django google-visualization