I have a dictionary that I am feeding into a chart.js line chart.
It looks as follows:
context['graph_data'] = {'day': [datetime.date(2022, 2, 28),
datetime.date(2022, 3, 1),
datetime.date(2022, 3, 2),
datetime.date(2022, 3, 3),
datetime.date(2022, 3, 4),
datetime.date(2022, 3, 5),
datetime.date(2022, 3, 6),
datetime.date(2022, 3, 7),
datetime.date(2022, 3, 8),
datetime.date(2022, 3, 9),
datetime.date(2022, 3, 10),
datetime.date(2022, 3, 11),
datetime.date(2022, 3, 12),
datetime.date(2022, 3, 13),
datetime.date(2022, 3, 14),
datetime.date(2022, 3, 15),
datetime.date(2022, 3, 16),
datetime.date(2022, 3, 17),
datetime.date(2022, 3, 18),
datetime.date(2022, 3, 19)],
'response_totals': [0,
0,
0,
0,
12,
12,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
1,
0,
0,
0]}
The template section that I am getting tripped up on looks like the following:
new Chart(ctx1, {
type: "line",
data: {
labels: [{%for i in graph_data%}{{i.day}},{%endfor%}],
datasets: [{
label: "Referrals",
tension: 0.4,
borderWidth: 0,
pointRadius: 2,
pointBackgroundColor: "#cb0c9f",
borderColor: "#cb0c9f",
borderWidth: 3,
backgroundColor: gradientStroke1,
data: [{%for j in graph_data%}{{j.response_totals}},{%endfor%}],
maxBarThickness: 6
},
I am a bit of a newbie. I can handle querysets but I'm not sure how to transform non-qs dictionaries via the template.
CodePudding user response:
You have a few ways to write this, first read up on the documentation for django template language.
Hopefully you understand that to get the list of days stored as a value against the day
key in python you would do something like context['graph_data']['day']
.
In the template we use .
to access dictionary keys, so we can use graph_data.day
in the template to get the same list of days that context['graph_data']['day']
would produce in python.
So I would do it like this:
new Chart(ctx1, {
...
data: {
labels:[{% for i in graph_data.day %}{{ i }},{% endfor %}],
...
}
}