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?
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 }}
}]
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With