Django with google charts

2019-07-17 17:52发布

问题:

I'm trying to get google charts displayed on my page, but i can't figure how to pass values from django views to javascript so i can draw charts.

Django code:

array = ([
      ['Year', 'Sales', 'Expenses'],
      ['2004',  1000,      400],
      ['2005',  1170,      460],
      ['2006',  660,       1120],
      ['2007',  1030,      540]
    ]);
args['array']= array
return render_to_response('progress.html',args)

progres.html :

<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() {
    var djangoData = '{{array}}';
    var data = google.visualization.arrayToDataTable(djangoData);

    var options = {
      title: 'Company Performance'
    };

    var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
    chart.draw(data, options);
  }
</script>

This way, the chart doesn't get displayed. Any suggestions ?

回答1:

google.visualization.arrayToDataTable() appears to take a 2D (javascript) array. What you are passing it is a string. You'll need to parse it into an array. Try:

var djangoData = JSON.parse('{{ array }}');
var data = google.visualization.arrayToDataTable(djangoData);


回答2:

In your view:

remove this line args['array']= array

change this line return render_to_response('progress.html',args) to return render_to_response('progress.html',{'array': json.dumps(array)})

In your template:

change this line var djangoData = '{{array}}'; to var djangoData = '{{ array | safe }}';

The rest of your code is fine. I hope this helps.



回答3:

for me this combination works:

view:

from django.shortcuts import render
import json

(...)
context= {'array': json.dumps(array)}
return render(request,'progress.html',context)

template:

var djangoData = JSON.parse('{{ array | safe }}';);