[Answer]-Passing values from django to google charts DataTable

1👍

Based on my experience, an example like below should work

<script type="text/javascript">
  google.load("visualization", "1", {packages:["corechart"]});
  google.setOnLoadCallback(drawChart);
  function drawChart() {
    var djangodata = {{djangodict|safe}};
    var data = google.visualization.arrayToDataTable();
    var options = {
        title: 'My Daily Activities'
        };
    var chart = new google.visualization.PieChart(document.getElementById('piechart'));
    chart.draw(data, options);
  }

In your view I suppose you can write something like; below

dictdata=[
    ['Task', 'Hours per Day'],
    ['Work',     11],
    ['Eat',      2],
    ['Commute',  2],
    ['Watch TV', 2],
    ['Sleep',    7]
    ]
return render_to_response{template,
                         'djangodict': json.dumps(dictdata),
                         .... other variables here
                         }

this should work fine if you are in the process of creating a template on its own for this chart. However declaring django variable as shown above in the script is very important.

var djangodata = {{djangodict|safe}};

Things might not work at all if you don’t 🙁

What I did was lil different to the above solution though. I actually created a templatetag to pass data variable to the above javascript and let it draw the chart as I wanted.
Simply because I wanted to include my charts on the dashboard page which that way works fine!

👤rreddy

Leave a comment