almost a beginner
almost a beginner

Reputation: 1632

Django data to Google Charts

View:

def home(request,
    template = 'home.html'):
    if request.user.is_authenticated():
        data = [['jan'],[12],[-12]]

    context = {
        'data' : data,
    }
    return render(
        request, template, context)

Template:

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawVisualization);

function drawVisualization() {


  var data = new google.visualization.DataTable();
  data.addColumn('string', 'Month');
  data.addColumn('number');
  data.addColumn('number');

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

  // Create and draw the visualization.
  new google.visualization.ColumnChart(document.getElementById('visualization')).
      draw(data,
           {title: "blabla",
            width:600, height:400,
            bar: { groupWidth: '90%' },
            isStacked:"true",
            legend:"none" }
      );

}
</script>

I'm trying to get the array values to the chart rows but don't understand why this is not working. No graph is draw, everything else works though.

The overall aim is to store model fields in an array then use it to draw the chart, if I can't do this then I won't be able to proceed.

When I call {{ data }} in the template, it returns:

[[0], [12], [-12]]

Is this the wrong format? How can I change this for Google Charts to accept it as row values?

Any help or direction would be appreciated,

thanks in advance

Upvotes: 3

Views: 1825

Answers (1)

WhiteHat
WhiteHat

Reputation: 61275

according to the data table definition in the code, there are three columns...

var data = new google.visualization.DataTable();
data.addColumn('string', 'Month');
data.addColumn('number');
data.addColumn('number');

but from reading the question, sounds like you only need two...

var data = new google.visualization.DataTable();
data.addColumn('string', 'Month');
data.addColumn('number');

and to add a single row of values, the format should be...

['Month', 0]

to add all the rows, using addRows, the format should be...

[
  ['Month',   0],
  ['Month',  12],
  ['Month', -12]
]

In your views context, change 'data' : data to 'data': json.dumps(data)

It is crucial to use json either in javascript, or in view.

Upvotes: 3

Related Questions