Reputation: 489
I'm creating a web application where I need to create a few charts. I'm using django 3 and ChartJS. I have created one list for the labels and one list for the data to be inserted into ChartJS. The problem I'm having is that no matter what I try or do the data just will not show up in the graph. When I try to access the data by writing it on the page it does work, but it does not work at all when inserting it into ChartJS for some reason.
According to the ChartJS documentation the data field can receive a list of values so I dont understand why this is not working.
I have searched quite a lot for solutions to this using google and stackoverflow and while I found some similar threads on stackoverflow, the solutions did not work for me. I tried converting to json, other ways of inserting the data, using a for loop etc, but nothing seems to work no matter what I do.
In the web application the labels and values are dynamically created, but at this time to troubleshoot the problem easier I have just created two lists by hand and tried to send them off to the template and insert them into ChartJS which does not work either.
This is the code I'm currently using:
views.py:
def check_spending(request):
graph_labels = ["Test1", "Test2", "Test3"]
graph_values = ["100", "50", "20"]
return render(request, 'spending/view_spending.html',
{'graph_labels': graph_labels,
'graph_values': graph_values})
HTML:
<!-- Values are printed out here -->
{{ graph_labels }}
{{ graph_values }}
for loop
{% for key in graph_labels %}
{{ key }}
{% endfor %}
<!-- Values does not work here -->
<canvas id="spending_overview_detailed" width="400" height="400"></canvas>
<script>
var ctx = document.getElementById('spending_overview_detailed');
var spending_overview_detailed = new Chart(ctx, {
type: 'bar',
data: {
labels: [{{ graph_labels }}],
datasets: [{
label: 'Spending',
data: [{{ graph_values }}],
borderWidth: 1
}],
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
</script>
Upvotes: 0
Views: 806
Reputation: 489
I ended up changing the labels and data field to the following:
[{% for label in graph_labels %} {{ label }}, {% endfor %}]
[{% for value in graph_values %} {{ value }}, {% endfor %}]
Notice the comma in the for loop, without it the values will not be processed correctly.
Upvotes: 2
Reputation: 783
{{ graph_labels }} and {{ graph_values }} are Django template variable and you are trying to access then inside javascript , this will not work. Use template tag "json_script" Django Documentation to pass data from django template to your javascript.
Upvotes: 0