在 JavaScript 折线图中添加列表数据 - Django 项目

Adding list data in a JavaScript line chart - Django project

我创建了一个列表并在我的 views.py 中定义了它:

mydata = [{'date': '2020-01-02T00:00:00Z', 'value': 13}, 
{'date': '2020-01-03T00:00:00Z', 'value': 2}, 
{'date': '2020-01-06T00:00:00Z', 'value': 5}]

我想在我的 HTML 文件中的模板 js 图表中添加我自己的数据:

<script>
var chart = am4core.create("chartdiv", am4charts.XYChart);
chart.paddingRight = 20;

var data = [];
var visits = 10;
for (var i = 1; i < 50000; i++) {
  visits += Math.round((Math.random() < 0.5 ? 1 : -1) * Math.random() * 10);
       data.push({
           date: new Date(2018, 0, i),
            value: visits
            });
      }

chart.data = data;

var dateAxis = chart.xAxes.push(new am4charts.DateAxis());
dateAxis.renderer.grid.template.location = 0;
dateAxis.minZoomCount = 5;

dateAxis.groupData = true;
dateAxis.groupCount = 500;

var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());

var series = chart.series.push(new am4charts.LineSeries());
series.dataFields.dateX = "date";
series.dataFields.valueY = "value";
series.tooltipText = "{valueY}";
series.tooltip.pointerOrientation = "vertical";
series.tooltip.background.fillOpacity = 0.5;

chart.cursor = new am4charts.XYCursor();
chart.cursor.xAxis = dateAxis;

var scrollbarX = new am4core.Scrollbar();
scrollbarX.marginBottom = 20;
chart.scrollbarX = scrollbarX;

var selector = new am4plugins_rangeSelector.DateAxisRangeSelector();
selector.container = document.getElementById("selectordiv");
selector.axis = dateAxis; 
  </script>  

我知道我应该更改 chart.data = data,但是当我将其替换为 chart.data = {{mydata}} 时,图表没有显示任何内容。我尝试手动更改它:chart.data = [{'date': '2020-01-02T00:00:00Z', 'value': 13}, {'date': '2020-01-03T00:00:00Z', 'value': 2}, {'date': '2020-01-06T00:00:00Z', 'value': 5}] 并且数据显示成功。

我确定我在 views.py 中正确导入了 mydata,因为我在 HTML 文件中测试了 {{mydata}},它显示了整个列表。我也尝试了 chart.data = {mydata}chart.data = mydatachart.data = [mydata],但其中 none 有效。

我自己解决了

在图表区,我简单地使用了:

chart.data = {{ mydata | safe }}