'How to get value of defaultdic in JS (Django framework)?

I want to use chartjs to display a chart on the page (Django framework).

views.py

chart_data = defaultdict(<class 'int'>, {'3': 2, '2': 2, '8': 2, '5': 2, '7': 1})
context["chart_data"] = chart_data

home.html

<script type="text/javascript">
  var my_chart = "{{ chart_data }}";
</script>

my_chart.js

  const data = {
    labels: labels,
    datasets: [{
      label: 'My First dataset',
      backgroundColor: 'rgb(255, 99, 132)',
      borderColor: 'rgb(255, 99, 132)',
      data: Object.values(my_chart),
    }]
  };

But it didn't work. When I used console.log(Object.values(my_chart)) to check, I found that what Object.values(my_chart) returns was ['d', 'e', 'f', 'a', 'u', 'l', 't', 'd', 'i', 'c', 't', '(', '&', 'l', 't', ';', 'c', 'l', 'a', 's', 's', ' ', '&', '#', 'x', '2', '7', ';', 'i', 'n', 't', '&', '#', 'x', '2', '7', ';', '&', 'g', 't', ';', ',', ' ', '{', '&', '#', 'x', '2', '7', ';', '3', '&', '#', 'x', '2', '7', ';', ':', ' ', '2', ',', ' ', '&', '#', 'x', '2', '7', ';', '2', '&', '#', 'x', '2', '7', ';', ':', ' ', '2', ',', ' ', '&', '#', 'x', '2', '7', ';', '8', '&', '#', 'x', '2', '7', ';', ':', ' ', '2', ',', ' ', '&', '#', …], it just disassembled each letter and symbol of the dictionary.

Do you know how can I get the value?



Solution 1:[1]

You should not pass javascript by rendering the object in the template. That will render it like the str(…) of the object. It is possible that for some objects, that will produce text that is a valid JavaScript expression, but often, as is here the case, it will not.

You can make use of the |json_script:… template filter [Django-doc] to render data as a JSON object, and then load this in a JavaScript script, so:

{{ chart_data|json_script:"my_chart" }}

<script type="text/javascript">
var my_chart = JSON.parse(document.getElementById('my_chart').textContent)
const data = {
    labels: labels,
    datasets: [{
      label: 'My First dataset',
      backgroundColor: 'rgb(255, 99, 132)',
      borderColor: 'rgb(255, 99, 132)',
      data: Object.values(my_chart),
    }]
  };
</script>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Willem Van Onsem