Chartjs-Passing data in array that came from an array to chartjs with django

0👍

Try this please

import csv

def home(request):
    csvFilePath = "../data/raw_datasets/covid_confirmed.csv"
    data_list = []
    with open(csvFilePath, "r") as csvfile:
        csv_reader = csv.reader(csvfile, delimiter=',')
        next(csv_reader)
        for row in csv_reader:
            data_list.append({'label' : row[73], "y" : row[1]})
    t = json.dumps(data_list)    

    return render(request, 'home.html',
                  {
                      'output':t
                  }) 

<!DOCTYPE html>

<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script>
        <title>Crypto Covid</title>
    </head>

    <body>

        <div id="pie-chart" style="width: 100%;height:370px;">
          </div> <!-- edited -->

    </body>


   <script src="https://canvasjs.com/assets/script/canvasjs.min.js"> <!-- edited--></script>
    <!-- edited -->
    data = JSON.parse("{{ output|escapejs }}")
    window.onload = function() {
    var chart = new CanvasJS.Chart("pie-chart", {
    type: 'pie',
    data: [{type: "pie",dataPoints: data}],
    options: {
      responsive: true
  }
});      
  chart.render();
};
</script>
</html>

0👍

you need to use template tag called json_script, {{ your_array|json_script:”chart_data” }} and then access this data in javascript –
var value = JSON.parse(document.getElementById(‘chart_data’).textContent);

https://docs.djangoproject.com/en/2.2/ref/templates/builtins/#json-scriptDjango documentation

0👍

Try passing the data list by list (I use render_template on Flask) and retrieve it on javascript (as an array) with:

labels: [{% for item in families %}
         "{{ item }}",
         {% endfor %}]

…even if pylint may say criticize the html syntaxe. It runs well.

Leave a comment