[Chartjs]-Generate multiple line charts in Django with ChartJS

0👍

You need to utilise the forloop.counter method in the django template to dynamically name a number of items, otherwise the charts will just get overwritten each time and you are just left with the last chart. Its worth noting that I include this code in the block content not a specific js block.

In the example below, the items that are dynamically named are;

  • The container div
<div id = 'emg-{{forloop.counter}}'>
  • The canvas
<canvas id="myChart-{{forloop.counter}}">
  • The chart JS function name
var func_name = "container-{{forloop.counter}}";
func_name = new Chart(
    document.getElementById('myChart-{{forloop.counter}}'),{
    type: 'scatter', 

I’ve included the full code below. I appreciate my example is different from your posted code, but it demonstrates the concept of dynamically creating certain elements.


    {% for time, name_list, value_list, latitude_list, longitude_list, polyline_list in data %}
    {% with forloop.counter as track_object_counter %}
    <div id = 'emg-{{forloop.counter}}'>
    {% for item in emg_data %}
    {% if item.loop_id == track_object_counter %}
    <div id = "emg-plot" style="height:15rem; padding-top: 1rem;">
      <canvas id="myChart-{{forloop.counter}}">
        <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
        <script>
          var y_data  = {{item.data|strip_apostrophe}}
          var x_data = '{{item.name}}'

          var func_name = "container-{{forloop.counter}}";
          func_name = new Chart(
            document.getElementById('myChart-{{forloop.counter}}'),{
              type: 'scatter',
              data: {
                datasets: [{
                  showLine: true,
                  label: x_data,
                  data:  y_data,
                  backgroundColor: 'rgba(141,49,123,0.7)',
                  borderWidth: 2,
                  borderColor: 'rgba(141,49,123,0.7)'
                }],
              },                              
          });
        </script>
      </canvas>
    </div>
    {% endif %}
    {% endfor %}
    </div>
    {% endwith %}
    {% endfor %}

Leave a comment