# Script issues when using chart.js in Django

**URL:** <https://forum.djangoproject.com/t/script-issues-when-using-chart-js-in-django/37144>\
**Category:** Templates & Frontend\
**Created:** [December 10, 2024, 10:15pm UTC](https://forum.djangoproject.com/t/script-issues-when-using-chart-js-in-django/37144 "2024-12-10T22:15:14Z")\
**Posts on this page:** 19\
**Page:** 1

<div class="post-metadata">

**Author:** ![jbhrfx9280](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/jbhrfx9280/32/15247_2.png) [@jbhrfx9280](https://forum.djangoproject.com/u/jbhrfx9280)\
**Post date:** [December 10, 2024, 10:15pm UTC](https://forum.djangoproject.com/t/script-issues-when-using-chart-js-in-django/37144/1 "2024-12-10T22:15:14Z")

</div>

Python 3.12.4  
Django 5.1.3

When using **chart.js** in Django and placing the script in the HTML page I get these weird JS errors. I have included a screen shot below as well as the code below that. I need to point out that it all **works perfectly**. The chart loads and the data is correct from the view query, no errors other than what I see in VSC on the html page.

I have a query view that generates the data and includes it in a context (normal stuff here) and rendering to an html page with

```auto
<canvas id="myChart" class="chart" width="400" height="200"></canvas>

```

set up and the script at the bottom of the page inside the body. **If I hover over each error I see things like:**  
Property assignment expected.javascript  
‘,’ expected.javascript  
Type annotations can only be used in TypeScript files.javascript  
Declaration or statement expected.javascript

What’s interesting if I take out this line

```auto
data: {{ data|safe }},

```

and replace it with this line with a hard var in it

```auto
data: myChartData,

```

**all the errors go away.** At first I thought maybe it was something to do with JS linting etc. But seem to not be. I appreciate all help on this. Thank you.

Screenshot of code in VSC with errors.

 ![{F8A25FF2-3442-495E-8626-02B91FB1C6A8}](https://us1.discourse-cdn.com/flex026/uploads/djangoproject/original/3X/5/f/5f622713816d450b7a8ee1d7b0409c8914c6bd5d.png)

Copy of script used

```auto
<script>
  var config = {
    type: 'bar',
    data: {
      datasets: [{
        label: "Epson NOC Monthly Totals", // label is what is printed at top of chart in the center
        data: {{ data|safe }},
        backgroundColor: [
            "rgba(255, 99, 132, 0.2)",
            "rgba(54, 162, 235, 0.2)",
            "rgba(255, 206, 86, 0.2)",
            "rgba(75, 192, 192, 0.2)",
            "rgba(153, 102, 255, 0.2)",
            "rgba(255, 159, 64, 0.2)",
          ],
          borderColor: [
            "rgba(255, 99, 132, 1)",
            "rgba(54, 162, 235, 1)",
            "rgba(255, 206, 86, 1)",
            "rgba(75, 192, 192, 1)",
            "rgba(153, 102, 255, 1)",
            "rgba(255, 159, 64, 1)",
          ],
          borderWidth: 1,
      }],
      labels: {{ labels|safe }}
    },
    options: {
      responsive: true
      }
  };

  window.onload = function() {
    var ctx = document.getElementById('myChart').getContext('2d');
    window.myBar = new Chart(ctx, config);
  };

</script>

```

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [December 10, 2024, 11:43pm UTC](https://forum.djangoproject.com/t/script-issues-when-using-chart-js-in-django/37144/2 "2024-12-10T23:43:14Z")

</div>

> [@jbhrfx9280](#):
>
> At first I thought maybe it was something to do with JS linting etc. But seem to not be.

What makes you think that the errors flagged _here_ are not simply a VSCode JS linting issue? The `{{ }}` notation is not valid JavaScript and isn’t going to pass.

Also, what is actually rendered and sent to the browser?

Looking at the actual JavaScript code as it has been rendered and sent to the browser would be more helpful in identifying the errors being reported in the browser.

---

<div class="post-metadata">

**Author:** ![jbhrfx9280](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/jbhrfx9280/32/15247_2.png) [@jbhrfx9280](https://forum.djangoproject.com/u/jbhrfx9280)\
**Post date:** [December 11, 2024, 12:33am UTC](https://forum.djangoproject.com/t/script-issues-when-using-chart-js-in-django/37144/3 "2024-12-11T00:33:37Z")

</div>

> [@KenWhitesell](#):
>
> The `{{ }}`

re: JSLint  
I did what VSC said to do and installed JSlint and enabled it and that did not fix it. I asked ChatGpt and github copilot and they suggested above.

re: {{ }}  
The use of `{{ }}` is what is used in more than 20 examples for chart.js in Django and is also from official charts site. Also Chatgpt and Gpt4all and github copilot use the same examples.

I did look at chrome dev tools response and because this is not causing an error and my lack of JS knowledge nothing jumped out.

After 6 hours nothing was jumping out at me.

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [December 11, 2024, 12:50am UTC](https://forum.djangoproject.com/t/script-issues-when-using-chart-js-in-django/37144/4 "2024-12-11T00:50:29Z")

</div>

**Using** the `{{ }}` is correct. However, it’s not JavaScript syntax, it’s Django Template Language. You shouldn’t expect a JavaScript linting tool to understand text that isn’t JavaScript.

If the code is working, then there is not a problem with the code. Therefore, the problem is with the tool saying that there is an error.

So fundamentally, yes, this is a linting issue, in that you’re expecting a lint tool to process a different language than that for which it is designed.

---

<div class="post-metadata">

**Author:** ![jbhrfx9280](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/jbhrfx9280/32/15247_2.png) [@jbhrfx9280](https://forum.djangoproject.com/u/jbhrfx9280)\
**Post date:** [December 11, 2024, 1:13am UTC](https://forum.djangoproject.com/t/script-issues-when-using-chart-js-in-django/37144/5 "2024-12-11T01:13:01Z")

</div>

What’s interesting is one of the suggestions was to put the code in a .Js file and it showed the same errors. So I do think your correct being a linting issue. I will do more troubleshooting based on your suggestions and see what I can find.  
I appreciate you’re help as always.  
Thank you

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [December 11, 2024, 1:34am UTC](https://forum.djangoproject.com/t/script-issues-when-using-chart-js-in-django/37144/6 "2024-12-11T01:34:49Z")

</div>

Technically, what you _should_ be doing is using the [json\_script](https://docs.djangoproject.com/en/5.1/ref/templates/builtins/#json-script) filter to separate your Django-supplied data from the JavaScript code. The data should be rendered into your template, and then your JavaScript code can copy that data into your JavaScript object.

---

<div class="post-metadata">

**Author:** ![philgyford](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/philgyford/32/14295_2.png) [@philgyford](https://forum.djangoproject.com/u/philgyford)\
**Post date:** [December 11, 2024, 8:32am UTC](https://forum.djangoproject.com/t/script-issues-when-using-chart-js-in-django/37144/7 "2024-12-11T08:32:09Z")

</div>

This is a good guide to passing your Django data to JavaScript in the template [How to Safely Pass Data to JavaScript in a Django Template - Adam Johnson](https://adamj.eu/tech/2022/10/06/how-to-safely-pass-data-to-javascript-in-a-django-template/#use-json-script-for-complex-values)

---

<div class="post-metadata">

**Author:** ![jbhrfx9280](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/jbhrfx9280/32/15247_2.png) [@jbhrfx9280](https://forum.djangoproject.com/u/jbhrfx9280)\
**Post date:** [December 11, 2024, 2:23pm UTC](https://forum.djangoproject.com/t/script-issues-when-using-chart-js-in-django/37144/8 "2024-12-11T14:23:07Z")

</div>

I appreciate all the guidance on this issue but still issues persist.  
I see that how I was using chart.js and passing the data was not secure. I have changed my code to fix this but now caused another issue.  
According to Django docs **json\_script** is a built in tag. It is part of the security middleware. You need to make sure your **settings.py** file has ‘ **django.middleware.security.SecurityMiddleware** ’, in **MIDDLEWARE:**

```auto
'django.middleware.security.SecurityMiddleware',

```

and insert **one** of the following in your HTML page

```auto
{% load security %}
or
{% load json_script %}

```

Either of these cause:  
**TemplateSyntaxError at /console\_app/**  
‘security’ is not a registered tag library. Must be one of:

Here is my code:

**views.py function (partial)**

```auto
data = {
        'labels': ['Messages', 'Ivanti', 'SolarWinds', 'Control-M', 'TurnOver Log'],
        'values': [53, 6, 27, 42, 100]   
    }
    template = 'console_app/base_console_ap.html'
    return render(request, template, {'chart_data': data})

```

**base\_console\_ap.html (partial)**

```auto
{% load security %}
or
{% load json_script %}

<canvas id="myChart" class="chart" width="400" height="200"></canvas>

<script src="{% static 'js/chart.min.js' %}"></script> 

<script>
  const chartData = JSON.parse(document.getElementById('chart-data').textContent);
  const ctx = document.getElementById('myChart').getContext('2d');
  const myChart = new Chart(ctx, {
      type: 'bar',
      data: {
          labels: chartData.labels,
          datasets: [{
              label: 'My Dataset',
              data: chartData.values,
          }]
      },
  });
</script>

<script id="chart-data" type="application/json">
  {{ chart_data|json_script:"chart-data" }}
</script>

```

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [December 11, 2024, 3:32pm UTC](https://forum.djangoproject.com/t/script-issues-when-using-chart-js-in-django/37144/9 "2024-12-11T15:32:59Z")

</div>

> [@jbhrfx9280](#):
>
> and insert **one** of the following in your HTML page

This is not correct. Neither of those `load` directives are needed. Neither is any specific middleware. This is a template filter and operates outside the context of any middleware.

Where are you getting this information?

---

<div class="post-metadata">

**Author:** ![jbhrfx9280](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/jbhrfx9280/32/15247_2.png) [@jbhrfx9280](https://forum.djangoproject.com/u/jbhrfx9280)\
**Post date:** [December 11, 2024, 4:25pm UTC](https://forum.djangoproject.com/t/script-issues-when-using-chart-js-in-django/37144/10 "2024-12-11T16:25:27Z")

</div>

I got this from the other gentleman that responded to this forum with a link to json\_script usage.

Yes reading Django docs it should **not** be needed, but I tried them anyways. When I remove the tags I do not get the error anymore nor does the chart work.  
When I drill down in the response and I see this :

![{060B5647-8D4A-4502-8B3E-37EFFED2E86E}](https://us1.discourse-cdn.com/flex026/uploads/djangoproject/original/3X/0/9/0923c59774cab97d303a967edabe8358144fd48c.png)

When I hover over the red x i see this:

```auto
Uncaught TypeError: Cannot read properties of null (reading 'textContent')

```

You can see from (_script id=“chart-data”_) that the **data** from the **view** is making it there.

```auto
<script>
  const chartData = JSON.parse(document.getElementById('chart-data').textContent);

  const ctx = document.getElementById('myChart').getContext('2d');
  const myChart = new Chart(ctx, {
      type: 'bar',
      data: {
          labels: chartData.labels,
          datasets: [{
              label: 'My Dataset',
              data: chartData.values,
          }]
      },
  });
  
</script>

<script id="chart-data" type="application/json">
  <script id="chart-data" type="application/json">"{\"labels\": [\"Messages\", \"Ivanti\", \"SolarWinds\", \"Control-M\", \"TurnOver Log\"], \"values\": [53, 6, 27, 42, 100]}"</script>
</script>

```

---

<div class="post-metadata">

**Author:** ![jbhrfx9280](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/jbhrfx9280/32/15247_2.png) [@jbhrfx9280](https://forum.djangoproject.com/u/jbhrfx9280)\
**Post date:** [December 11, 2024, 4:44pm UTC](https://forum.djangoproject.com/t/script-issues-when-using-chart-js-in-django/37144/11 "2024-12-11T16:44:48Z")

</div>

I have also adjusted the script to make sure the DOM is loading before the script runs

```auto
<script>
document.addEventListener('DOMContentLoaded', function () {
    
  const chartData = JSON.parse(document.getElementById('chart-data').textContent);

  const ctx = document.getElementById('myChart').getContext('2d');
  const myChart = new Chart(ctx, {
      type: 'bar',
      data: {
          labels: chartData.labels,
          datasets: [{
              label: 'My Dataset',
              data: chartData.values,
          }]
      },
  });
});
</script>

```

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [December 11, 2024, 5:07pm UTC](https://forum.djangoproject.com/t/script-issues-when-using-chart-js-in-django/37144/12 "2024-12-11T17:07:15Z")

</div>

> [@jbhrfx9280](#):
>
> ```auto
> <script id="chart-data" type="application/json">
> <script id="chart-data" type="application/json">"{\"labels\": [\"Messages\", \"Ivanti\", \"SolarWinds\", \"Control-M\", \"TurnOver Log\"], \"values\": [53, 6, 27, 42, 100]}"</script>
> </script>
> 
> ```

You’ve got two elements here with the same HTML `id` attribute. This is an error, the `id` attribute must be unique on a page.

---

<div class="post-metadata">

**Author:** ![jbhrfx9280](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/jbhrfx9280/32/15247_2.png) [@jbhrfx9280](https://forum.djangoproject.com/u/jbhrfx9280)\
**Post date:** [December 11, 2024, 5:30pm UTC](https://forum.djangoproject.com/t/script-issues-when-using-chart-js-in-django/37144/13 "2024-12-11T17:30:34Z")

</div>

Hmm, That’s interesting. The code is:

```auto
<script id="chart-data" type="application/json">
  {{ chart_data|json_script:"chart-data" }}
</script>

```

The response is what u pointed out. So I changed it:

```auto
<script>
    
  const chartData = JSON.parse(document.getElementById('chart-data1').textContent);

  const ctx = document.getElementById('myChart').getContext('2d');
  const myChart = new Chart(ctx, {
      type: 'bar',
      data: {
          labels: chartData.labels,
          datasets: [{
              label: 'My Dataset',
              data: chartData.values,
          }]
      },
  });

</script>

<script id="chart-data1" type="application/json">
  {{ chart_data|json_script:"chart-data" }}
</script>

```

and the response still shows the data accurately. Same original error.

```auto
<script id="chart-data1" type="application/json">
  <script id="chart-data" type="application/json">"{\"labels\": [\"Messages\", \"Ivanti\", \"SolarWinds\", \"Control-M\", \"TurnOver Log\"], \"values\": [53, 6, 27, 42, 100]}"</script>
</script>

```

---

<div class="post-metadata">

**Author:** ![jbhrfx9280](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/jbhrfx9280/32/15247_2.png) [@jbhrfx9280](https://forum.djangoproject.com/u/jbhrfx9280)\
**Post date:** [December 11, 2024, 5:54pm UTC](https://forum.djangoproject.com/t/script-issues-when-using-chart-js-in-django/37144/14 "2024-12-11T17:54:44Z")

</div>

I have used the example that Django docs shows and still same results.

> **[Built-in template tags and filters | Django documentation](https://docs.djangoproject.com/en/5.1/ref/templates/builtins/#json-script)**
>
> The web framework for perfectionists with deadlines.

```auto
<script id="hello-data" type="application/json">{"hello": "world\\u003C/script\\u003E\\u0026amp;"}</script>

```

With my changes:

```auto
<script id="chart-data" type="application/json">{{ chart_data|json_script:"chart-data" }}</script>

```

response:

```auto
<script id="chart-data" type="application/json"><script id="chart-data" type="application/json">"{\"labels\": [\"Messages\", \"Ivanti\", \"SolarWinds\", \"Control-M\", \"TurnOver Log\"], \"values\": [53, 6, 27, 42, 100]}"</script></script>

```

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [December 11, 2024, 6:08pm UTC](https://forum.djangoproject.com/t/script-issues-when-using-chart-js-in-django/37144/15 "2024-12-11T18:08:53Z")

</div>

> [@jbhrfx9280](#):
>
> `<script id="hello-data" type="application/json">{"hello": "world\\u003C/script\\u003E\\u0026amp;"}</script>`

This is _not_ what the docs are telling you to use. This is the sample output from having done what the previous sample describes.

The example that you _code_ is the block above that.

> {{ value|json\_script:“hello-data” }}

It’s _that_ line of code generating the **output** that you’re quoting above.

---

<div class="post-metadata">

**Author:** ![jbhrfx9280](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/jbhrfx9280/32/15247_2.png) [@jbhrfx9280](https://forum.djangoproject.com/u/jbhrfx9280)\
**Post date:** [December 11, 2024, 6:42pm UTC](https://forum.djangoproject.com/t/script-issues-when-using-chart-js-in-django/37144/16 "2024-12-11T18:42:15Z")

</div>

Yes only put that there as an example. Of course I changed it as I put below that example.

So I did make another change and it works now.

I added this above the script:

```auto
{{ chart_data|json_script:"chart-data" }}

```

I removed this script from the bottom:

```auto
<script id="chart-data" type="application/json">{{ chart_data|json_script:"chart-data" }}</script>

```

Now Code looks like this :

```auto
{{ chart_data|json_script:"chart-data" }}

<script>
  const chartData = JSON.parse(document.getElementById('chart-data').textContent);
  const ctx = document.getElementById('myChart').getContext('2d');
  const myChart = new Chart(ctx, {
      type: 'bar',
      data: {
          labels: chartData.labels,
          datasets: [{
              label: 'My Dataset',
              data: chartData.values,
          }]
      },
  });
</script>

```

And now the response returned from view is:

```auto
<script id="chart-data" type="application/json">{"labels": ["Messages", "Ivanti", "SolarWinds", "Control-M", "TurnOver Log"], "values": [53, 6, 27, 42, 100]}</script>

<script>
  const chartData = JSON.parse(document.getElementById('chart-data').textContent);
  const ctx = document.getElementById('myChart').getContext('2d');
  const myChart = new Chart(ctx, {
      type: 'bar',
      data: {
          labels: chartData.labels,
          datasets: [{
              label: 'Epson NOC Monthly Totals',
              data: chartData.values,
          }]
      },
  });
</script>

```

Works great.

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [December 11, 2024, 6:58pm UTC](https://forum.djangoproject.com/t/script-issues-when-using-chart-js-in-django/37144/17 "2024-12-11T18:58:47Z")

</div>

That’s the way to do it!

---

<div class="post-metadata">

**Author:** ![jbhrfx9280](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/jbhrfx9280/32/15247_2.png) [@jbhrfx9280](https://forum.djangoproject.com/u/jbhrfx9280)\
**Post date:** [December 11, 2024, 8:13pm UTC](https://forum.djangoproject.com/t/script-issues-when-using-chart-js-in-django/37144/18 "2024-12-11T20:13:53Z")

</div>

Thank you Ken. I appreciate all your support. I know you give a lot.

---

<div class="post-metadata">

**Author:** ![philgyford](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/philgyford/32/14295_2.png) [@philgyford](https://forum.djangoproject.com/u/philgyford)\
**Post date:** [December 11, 2024, 9:18pm UTC](https://forum.djangoproject.com/t/script-issues-when-using-chart-js-in-django/37144/19 "2024-12-11T21:18:50Z")

</div>

> [@jbhrfx9280](#):
>
> I got this from the other gentleman that responded to this forum with a link to json\_script usage.

I’m not sure where you got the information about needing to load `security` or `json_script` - those instructions are not in [the page I linked to](https://adamj.eu/tech/2022/10/06/how-to-safely-pass-data-to-javascript-in-a-django-template/#use-json-script-for-complex-values).

But I’m glad you got it all working, well done!
