Chartjs-Grouped bar dataset in djanog template loop

0👍

Rather than processing the values in template, why not you build the dataset in view and send it as context, like this:

datasets = list()

for label, color, data in zip(label_list, color_list, data_list):
    value_dict = {
         'label': label,
         'backgroundColor' : color,
         'data': data
    }
    datasets.append(value_dict)

context = {'datasets': json.dumps(datasets)}  # use 'import json' on top of the file
return render('template.html', context)

Then use it directly in your template like this:

<script>
    var dataset = {{ datasets }}
    // rest of the code
</script>

Leave a comment