Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying a Google Chart Using Django

I have generated a variable data in Django with the following format:

data = [['100',10],['90',9],['80',8]]

and I've passed it off to my template using render_to_response:

return render_to_response('template.html', {
                                            'data': data,
                                            },
                                            context_instance=RequestContext(request))

In the template header I have placed a call to Google Charts to generate a line chart:

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
  var data = new google.visualization.DataTable();
  data.addColumn('string', 'Number');
  data.addColumn('number', 'Number/10');
  data.addRows( {{ data }} );

var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240, title: "Numbers"});
}
</script>

When I do this, nothing is displayed. If I strip the strings out of data and try again, the chart appears, but obviously with no x-axis labels.

I have also tried adding the data using the arrayToDataTable function:

var data = google.visualization.arrayToDataTable([
      ['Number', 'Number/10'],
      {% for datum in data %}
          {{ datum }},
      {% endfor %}],
      false);

but this again fails to display any chart.

Any suggestions on how I can change one of the above, or try another approach to get the x-axis labels to appear?

like image 1000
Sinidex Avatar asked Sep 15 '11 00:09

Sinidex


1 Answers

You have to disable the autoescaping of your results. You can do so by adding the safe filter:

data.addRows( {{ data|safe }} );

or

{% autoescape off %}
[...]
    {{ data }}
[...]
{% endautoescape %}

My advice is, if you can install additional packages, to use one of these wrappers:

http://code.google.com/p/google-chartwrapper/

https://github.com/jacobian/django-googlecharts/

I can't add more than two links yet but another one is located here: code.google.com/p/django-graphs/

like image 155
Nelloverflow Avatar answered Nov 11 '22 19:11

Nelloverflow