I created a list and defined it in my 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}]
I want to add my own data in a template js chart in my HTML file:
<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>
I know I should change the chart.data = data, but when I replaced it with chart.data = {{mydata}}, the chart didn't display anything. I tried change it manually: 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}] and the data was displayed successfully.
I'm sure I imported mydata correctly in views.py, because I tested {{mydata}} in the HTML file, it showed the whole list. I also tried chart.data = {mydata}, chart.data = mydata and chart.data = [mydata], but none of them worked.
I solved it by myself.
In the chart area, I simply used:
chart.data = {{ mydata | safe }}