Getting data from Django models to Google Charts

Viewed 933

I'm trying to displays charts of the most sold items in the store. So I would need to take information from the database and into the html. The charts don't seem to load. When I tried static data (the examples from Google), it works fine. However, I cannot seem to do it with dynamic data. I converted the array into a json and did the |safe in the html for escaping. Yet still it doesn't appear. If anyone has an tips on how to fix it, please help!

Below is my views.py where I call the html file that has the script of charts.

def charts(request):
    data_arr = []
    for item in Item.objects.all():
        data_arr.append([item.ItemName, item.quantity_sold])
    return render(request,'coffeeapp/charts.html',{'item':json.dumps(data_arr)})

Here is my code in the charts.html file

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

        function drawChart() {
            // Define the chart to be drawn.
            var data = google.visualization.arrayToDataTable(
                ['Item', 'Quantity Sold'],
                [{{item|safe}}]
            );
            
            // Instantiate and draw the chart.
            var chart = new google.visualization.PieChart(document.getElementById('myPieChart'));
            chart.draw(data, null);
        }
    </script>

    <!--Div that will hold the pie chart-->
    <div id="myPieChart"/>

EDIT 1: What is in {{item|safe}}

I've printed out item in views.py and this is the result:

[["Espresso", 0], ["Cappuccino", 2], ["Black Coffee", 0], ["Cafe Latte", 0], ["Mocha", 0], ["Iced Americano", 0]....

In the browser/html, I've added an alert({{item|safe}}) as the first line under function drawChart() and it shows the items accurately from what I see. Some results are as follows

Espresso,0,Cappuccino,2,Black Coffee,0,Cafe Latte,0,Mocha,0,Iced Americano,0,Iced Caramel Macchiato,0,Cold Brew,0....

EDIT 2 - SOLUTION

With help of Marco's answer, I was able to fix this issue. Marco had the answer to fixing the labels but the data rows were static meaning manually entered whereas I wanted to get it from the database. As such I had modified my views to be this.

def charts(request):
    return render(request,'coffeeapp/charts.html',{'item':Item.objects.all()})

And my html to be:

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

        function drawChart() {
            // Define the chart to be drawn.
            
        var data = google.visualization.arrayToDataTable([
            [{ label: 'Item', type: 'string' },
            { label: 'Quantity Sold', type: 'number' }],
            {% for i in item %}
                ['{{ i.ItemName }}', {{ i.quantity_sold }}],
            {% endfor %}
        ]);
        var options = {
            'title': 'MOST ORDERED DRINKS',
            'width': 700,
            'height': 700
        };
        // Instantiate and draw the chart.
        var chart = new google.visualization.PieChart(document.getElementById('myPieChart'));
        chart.draw(data, options);
        }

    </script>

I am unsure on how it works but it does without the safe keyword.

2 Answers

Check closely your chart settings - it seems you need more settings for create the labels of the pie chart.

This is the working configuration:

  // Define the chart to be drawn.
  // Data settings = modified for generate the Pie Chart: 
  var data = google.visualization.arrayToDataTable([
    [{label: 'Item', type: 'string'}, 
     {label: 'Quantity Sold', type: 'number'}],
    ['Espresso', 0],
    ['Cappuccino', 2],
    ['Black Coffee', 0],
    ['Cafe Latte', 0],
    ['Mocha', 0],
    ['Iced Americano', 0],
    ['Iced Caramel Macchiato', 0],
    ['Cold Brew', 0]
  ]);

With the information you provided in your question, I've modified the code and I see the chart generated.

N.B: you have values with 0, so, if all values are zero, no chart will be generated, in your sample data, only 1 coffe has a value greater than zero:

    ['Cappuccino', 2], // This is the value that will show in the chart.

This is the working jsfiddle.

google.charts.load('current', {
  packages: ['corechart']
});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
  // Define the chart to be drawn.
  // Data settings = modified for generate the Pie Chart: 
  var data = google.visualization.arrayToDataTable([
    [{
        label: 'Item',
        type: 'string'
      },
      {
        label: 'Quantity Sold',
        type: 'number'
      }
    ],
    ['Espresso', 0],
    ['Cappuccino', 2], // This is the value that will show in the chart.
    ['Black Coffee', 0],
    ['Cafe Latte', 0],
    ['Mocha', 0],
    ['Iced Americano', 0],
    ['Iced Caramel Macchiato', 0],
    ['Cold Brew', 0]
  ]);

  // Instantiate and draw the chart.
  var chart = new google.visualization.PieChart(document.getElementById('myPieChart'));
  chart.draw(data, null);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="myPieChart" />

in views.py

def send_data(request):
    # get data ...
    # convert to dual items in tuple, dictionary, list & etc...
    return render(request, 'template_name', context={'data':data})

in javascript file

const draw_chart = (data) => {
    // draw chart....
}

in template html file

<script>
    draw_chart({{ data }})
</script>
Related