Django json_script variables not updating in javascript for loop

In my django project I have a for loop that iterates through a list of dicts containing a list of prices and and a list of dates. The lists of prices and dates for each item will then be used for a javascript graph for each individual item.

The problem is that all of the graphs are the same. When outputting prices and dates in the console each list of prices and dates are the same as the first element in the list of items.

Why is this happening?

console output - (sw0_ _ _ is the ID of each item)

enter image description here

html

{% for item in watchlist_items %}

<canvas id="chart_{{item.item_id}}"></canvas>

{{ item.prices|json_script:"prices" }}
{{ item.dates|json_script:"dates" }}
<script>

    var prices = JSON.parse(document.getElementById('dates').textContent);
    var dates = JSON.parse(document.getElementById('prices').textContent);

    var data = [];
    for (let i = 0; i < prices.length; i++) {
        data.push({x:prices[i], y:dates[i]});
    }

    console.log(`chart_{{item.item_id}} - `, "prices:",prices, "dates:", dates)
    
    new Chart(`chart_{{item.item_id}}`, {
        ...
        data: {
            data:data
        }
        ...
    }

</script>

{% endfor %}
Back to Top