Chart.js not rendering

Viewed 686

I have been using and learning Flask with python recently, and was looking to use some charts to visualize some data. I straight up followed a youtube guide and used almost the exact same code to visualize my data, but it didnt work. So, i tried using his exact code and still, it did not render the chart. What might be the issue?

from flask import flask, render template

app = flask(__name__)

data = [
    ("01-01-2020", 1597),
    ("02-01-2020", 1456),
    ("03-01-2020", 1908),
    ("04-01-2020", 896),
    ("05-01-2020", 755),
    ("06-01-2020", 453),
    ("07-01-2020", 1100),
    ("08-01-2020", 1235),
    ("09-01-2020", 1478),
]
labels = [row[0] for row in data]
values = [row[1] for row in data]

return render_template("graph.html", labels=labels, values=values)

the above is a part of my python app, below is the HTML that goes with it:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title> Sample chart </title>
  <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4/dist/Chart.min.js"></script>
</head>


<body>
    <canvas id="lineChart" width="900" height="400"></canvas>
    <script>
        var ctx = document.getElementById("lineChart").getContext("2d");
        var lineChart = new Chart(ctx, {
            type: "line",
            data: {
                labels: {{ labels | safe }}
                datasets: [
                    {
                        label: "Data points",
                        data: {{ values | safe }}
                        fill: true,
                        borderColor: "rgb(75, 192, 192)",
                        lineTension: 0.1
                    }
                ]
            },
            options: {
                responsive: false
            }
        });
    </script>
</body>
</html> 

When i load my localhost, the page is empty. just nothing. If i put in this above, it renders just fine:

<p> {{ labels }} </p>

When i inspect the web page, i can see all the html code, however, in the console when i inspect, there is an error:

Uncaught SyntaxError: Unexpected indetifier
example:17

Tried to google it a bit but didnt really get anything i understood to use. So, any ideas on what might be the issue?

(Also, i would link the youtube video but im a bit unsure about the rules and if i can even copy his code in here?)

1 Answers

you have to use or import chart js library by or else go through documentation first

like this if you are using CDN

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.0.2/chart.min.js" ></script>
Related