Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could I pass data to chart.js with flask?

I recently trying to make dashboard which datas from mongodb with flask. But I cannot send datas to chart.js. I got the data from mongodb and send to javascript and try to loop data with jinja2.

@app.route("/dashboard")
def dashboard():
    limit = request.args.get("limit",12,type=int)
    dashboardDatas = mongo.db.dashBoard
    dashDatas = dashboardDatas.find().limit(limit)

    return render_template("dashboard.html", dashDatas = dashDatas)
        <canvas id="myChart" height="50"></canvas>

        <script>
            var ctx = document.getElementById('myChart').getContext('2d');
            var myChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: [ {% for item in dashDatas %} 
                                '{{item._id}}', 
                                {% endfor %} ],
                    datasets: [{
                        label: '# of Votes',
                        data: [ {% for item in dashDatas %}
                                {{item.logistic}},
                                {% endfor %}],
                        borderColor: [
                            'rgba(255, 99, 132, 1)',
                        ],
                        backgroundColor: [
                            'rgba(255, 99, 132, 0.2)',
                        ],
                        borderWidth: 0.5
                    }]
                },
                options: {
                    scales: {
                        yAxes: [{
                            ticks: {
                                beginAtZero: true
                            }
                        }]
                    }
                }
            });
            </script>

And I got empty chart. What did I do wrong?

like image 679
bluesky Avatar asked Oct 29 '25 11:10

bluesky


1 Answers

My approach is to store the labels and data in lists in the Flask view, pass them to the template and transform them to JSON with the tojson filter.

Suppose you have labels = ['a', 'b', 'c'] and data = [1, 2, 3] in your view. You can pass them to Chart.js in your template as

let chart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: {{ labels|tojson }},
    datasets: [{
      label: 'My 1st dataset',
      backgroundColor: 'rgb(255, 99, 132)',
      borderColor: 'rgb(255, 99, 132)',
      data: {{ data|tojson }}
  }]
});
like image 100
Simeon Nedkov Avatar answered Nov 01 '25 00:11

Simeon Nedkov