Reputation: 31
I'm trying to use google charts
to visualize some data. As described in docs, i put this code to my template
:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var tmp = document.getElementById('result').value;
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]]
);
var options = {
title: 'Company Performance',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
And it works fine. But i need to pass some custom data, so i did:
views.py
:
def home(request):
example = [
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
]
return render(request, 'home.html', {'example': example})
As example data i used the same array. Next i replaced array in javascript code to {{ example }}
:
var data = google.visualization.arrayToDataTable( {{example}} );
And nothing happens. Google chart isn't drawing on my webpage anymore.
What im doing wrong? Also i tried to use json.dumps
in python code and it didn't worked for me.
Upvotes: 1
Views: 544
Reputation: 28732
You should simply turn your list of lists into valid json before you pass it to the template:
import json
def home(request):
example = [
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
]
example = json.dumps(example)
return render(request, 'home.html', {'example': example})
Make sure you're using the safe
template tag:
var data = google.visualization.arrayToDataTable( {{example|safe}} );
What is the error you're getting when you try that?
Upvotes: 1