I'm trying to draw a line chart using "https://www.google.com/jsapi", and passing data from a Django view;
this is my template
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
data = {{analytics_data}}
var data = google.visualization.arrayToDataTable(data);
var options = {
title: 'Facebook Analytics'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
views.py
def show_fb_analytics(request):
analytics_data = [["Day", "Likes", "Share", "Comments"]]
data = FbAnalytics.objects.all()
for item in data:
date = item.date
likes = item.likes
comments = item.comments
shares = item.shares
lst = [date, likes, comments, shares]
analytics_data.append(lst)
return render(request, 'fbchart.html', {'analytics_data':analytics_data})
The analytics_data should return data in format
[['Day', 'Likes', 'Share', 'Comments'],
['31 Aug', 5, 8, 10 ],
['01 Sep', 10, 5, 13 ]]
but during render of the html template it gives data it given format
[['Day', 'Likes', 'Share', 'Comments'],
[u'01Sep', 2, 2, 2]]
means it is adding u'' in every string due to which I'm getting the error "Uncaught Syntax Error: Unexpected token &" and my temlate is not returning the line chart. How I can remove this error?
You should convert your list to proper JSON first, like this:
import json
def show_fb_analytics(request):
...
return render(request, 'fbchart.html', {'analytics_data': json.dumps(analytics_data)})
Then output it with "safe" filter, so Django's escaping engine doesn't intervene:
{{analytics_data|safe}}
Converting to JSON will output your list as JavaScript Array literal (instead of Python List literal; although the two are pretty similar, they are in fact different, in your case Python has u
prefixes which JS doesn't, etc.), and using safe
filter will prevent Django's template engine from converting '
to '
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With