I am using Chart.js and Flask to make a dashboard.
I am trying to make a chart.js graph based on the response posted from the form. However, when I try creating the Chart.js graph it does not appear.
Can someone please tell me what I am doing wrong? Thanks!
Flask Code:
from flask import Flask, render_template, request
import data_analysis as analysis
app = Flask(__name__)
df = analysis.initialize()
@app.route('/')
@app.route('/home')
def home():
return render_template('data.html', title="title", df=df.head())
@app.route('/dashboard', methods = ['POST', 'GET'])
def dashboard():
column_name = str(request.form.get('select1'))
# default use first column
data = analysis.create_count_bars(df.columns[0])
labels = list(data[0].keys())
values = list(data[0].values())
# else
if (column_name != "None"):
data = analysis.create_count_bars(column_name)
labels = list(data[0].keys())
values = list(data[0].values())
return render_template('dashboard.html', title="title", df=df.head(), labels=labels,
values=values, xlabel = data[1], ylabel = data[2], column_name=column_name)
HTML/ Chart.js Code ("dashboard.html"):
{% block header %}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
{% endblock %}
{% block menubar %}
<div class="navbar">
<ul>
<li><a href="/home"> Home </a></li>
<li><a class="active" href="/dashboard"> Dashboard </a></li>
</ul>
</div>
{% endblock %}
{% block content %}
<div id = "survey">
<form method="POST" action="{{ url_for('dashboard') }}">
<label for="Columns">Choose a column to graph: </label>
<select name="select1" id="select1">
{% for column in df %}
<option value="{{column}}">{{column}}</option>
{% endfor %}
</select>
<br><br>
<input type="submit" value="Submit">
</form>
</div>
<div class="charts">
<canvas id="barChart" width="600" height="400"></canvas>
</div>
{% endblock %}
{% block script %}
<script>
const ctx = document.getElementById("barChart").getContext("2d");
const labels = [{{ labels|safe }}];
const data = {
labels: labels,
datasets: [{
label: {{ ylabel|safe }},
backgroundColor: '#CE3B21',
borderColor: 'rgb(255, 99, 132)',
data: {{ values|safe }},
}]
};
const config = {
type: "bar",
data: data,
options: {
responsive: true,
scales: {
y: {
beginAtZero: true
}
}
}
};
const chart = new Chart(ctx, config);
chart
</script>
{% endblock %}
DevTools
in Chrome/Firefox and check tabNetwork
to see if it loadschart.js
. And next you can check tabConsole
to see if it display JavaScript errors. You could also check HTML in browser to see if values are correct in JavaScript . Maybe it will need to convert lists to JSON or add" "
to strings. – furasstr()
fromrequest.form.get('select1')
and checkif column_name is not None:
or shorterif not column_name:
– furas