Sinidex
Sinidex

Reputation: 503

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?

Upvotes: 6

Views: 14677

Answers (1)

Nelloverflow
Nelloverflow

Reputation: 1756

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:

Upvotes: 12

Related Questions