Guide to displaying Django data on a Chart.js visualization

Feeling absolutely frustrated, I've been struggling with implementing chart.js on my Django website. All I want to do is plot two fields: Dates and Scores. Dates are in the format of `1/6/2022`, while scores are floats. The problem arises when passing a Python list to the script – it just doesn't cooperate. Strangely enough, manually inputting the list directly into the chart's data works perfectly fine. It's as though the script refuses to recognize it as a variable, which makes no sense at all. I've scoured the internet for answers, but haven't found anything helpful.

views.py

def progress(response):

    lessons = StudentLessons.objects.get(name=response.user.email)

    scores = []
    dates = []
    for lesson in lessons.lesson_set.all():
        dates.append(str(lesson.date))
        scores.append(str((lesson.accuracy+lesson.speed+lesson.understanding)/3))

    context = {
        'dates': dates,
        'scores': scores,
    }

    return render(response, "main/progress.html", context)

dates = ['2022-09-27', '2022-09-28'] scores = ['4.333333333333333', '6.0'] (from console) Correctly displayed chart HTML:

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>  

<canvas id="myChart" style="width:100%;max-width:700px"></canvas>

<script type="text/javascript">

    var myChart = new Chart("myChart",{
        type:"line",
        data: {
            labels: ['2022-09-27', '2022-09-28'],
            datasets:[{
                borderColor: "rgba(0,0,0,0.1)",
                data: ['4.333333333333333', '6.0']
            }]
        },
        options:{
            responsive: true,
            legend: {
                position: 'top',
             },
        }
    });

</script>

HTML that doesn't work:

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>  

<canvas id="myChart" style="width:100%;max-width:700px"></canvas>

<script type="text/javascript">

    var myChart = new Chart("myChart",{
        type:"line",
        data: {
            labels: {{dates}},
            datasets:[{
                borderColor: "rgba(0,0,0,0.1)",
                data: {{scores}}
            }]
        },
        options:{
            responsive: true,
            legend: {
                position: 'top',
             },
        }
    });

</script>

I would greatly appreciate any assistance with this issue. It's driving me crazy, and it's the final piece of the puzzle I need to solve.

Answer №1

When working with JavaScript, remember to wrap the context keys in "{{ and }}". In your HTML code, make sure to update dates and scores as "{{dates}}" and "{{scores}}". Also, be mindful of using the correct tags and filters. For more information, check out the documentation.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Getting Errors When Retrieving Data with Apostrophe Symbol ' in Node.js

I am currently developing a Next.js API page to extract data from a series of URLs. Interestingly, the URLs containing an apostrophe character ' fail to return any data, while those without it work perfectly fine. Surprisingly, when I execute the same ...

Struggling to construct an Angular 4 project with systemjs integration

I'm currently working with Angular 4 and VS 2017 (ASP.NET Core 5 Web Api) along with systemjs. I am in the process of preparing my Angular application for production. To achieve this, I have added two dependencies in my package.json "devDependenc ...

Having trouble determining the total amount in my online shopping cart

I am facing an issue with the shopping cart I created, which consists of two components (Productlist and Cart List). When I click on the 'add to cart' button in the Product List, it successfully moves into the service file and then to the Cart Li ...

Unforeseen Name Conflict issue

The issue I'm facing with Mongo involves an identifier in the forEach loop within the second aggregation. Despite my best efforts, I cannot pinpoint which identifier is causing the problem. After staring at it all day, I realize that fresh eyes are ne ...

Navigating through each div element one by one

Despite the unfortunate title, my current setup involves a dynamic form with tasks and statuses. The number of tasks and statuses can vary. I am aiming to submit the task name, status name, and colors associated with each status. <form> <div c ...

What is the best way to ensure that a model field only accepts incremental numbers in my model?

In my Django model, I have the following setup: class Page(models.Model): page_number = models.IntegerField() ... I want to ensure that the page numbers are always a sequential series of integers without any gaps. Even if I delete pages in between ...

Vue- async function results in a Promise object with a status of <pending>

Hey everyone, I could use some assistance with my Vue code. Here's the issue: I'm attempting to retrieve data (specifically anime) from an online anime API. In my project, I have two files: Anime.vue (the view page) and getAnime.js (which house ...

Verifying the presence of an image via its URL may not be functional across all browsers

Hey folks, I'm working on a project that involves displaying an image along with other fields in a loop where the image source changes with each iteration. I also need to check if the image exists and set a default source if it doesn't. The code ...

How do you achieve the same effect as <Redirect to="/login" /> with the Navigate component in react-router-dom v6?

When utilizing react-router-dom v5, I had the following code snippet that would direct users to the login page if they weren't authenticated, or to the rest of the application if they were: !isAuthenticated ? ( <> ...

Using jQuery or JavaScript, extract JSON data from Yahoo Pipes

Here is the JSON format that I receive from Yahoo pipes: {"count":3, "value":{ "title":"Freak count feed", "description":"Pipes Output", "link":"http:\/\/pipes.yahoo.com\/pipes\/pipe.info?_id=565sdf6as5d4fas ...

Animation effects for a menu using jQuery

I am in the process of creating a website and I have incorporated jQuery to add animation to a horizontal tabbed menu. The effect that I am aiming for can be viewed here: / link removed / When you hover over the "Link 1" tab, you will notice a white div ...

Set the value obtained from a resolved promise to a mutable reference object in a React component

I am in the process of developing a random movie generator. I am utilizing an external API to retrieve a list of movies and then selecting one randomly from the returned data. The current implementation is as follows: export default function Page() { con ...

Displaying information in an alert box with the use of JavaScript

Every time I attempt to display data in an alert box upon button click, I encounter an issue where the alert box fails to populate. Here is what I have tried: <head runat="server"> <title></title> <script type="text/javascript" s ...

Using AngularJS to dynamically bind data based on certain conditions

I am managing an array of tasks that each have titles and labels. function Task(taskTitle, taskType) { this.title = taskTitle; this.type = taskType; } $scope.tasks = []; As I create different tasks with various types and add them to the array. In ...

Exploring the world of Ember through engaging click events

Exploring EmberJS and in the process of transitioning an existing website to this framework, I encountered a challenge with a Bootstrap-based dropdown. While troubleshooting this issue, I found that it deepened my understanding of Ember's concepts, al ...

Is it possible to delay Vue rules from validating until a user interacts with an element?

For a project I am working on, I have implemented a v-date-picker where users can select a departure date and a return date. Interestingly, while most of the input field validations only occur after user interaction, the departure date picker displays an e ...

Error message encountered: Missing property status in TypeScript code

An error occurs in the refetchInterval when accessing data.status, with a message saying "property status does not exist" chatwrapper.tsx const ChatWrapper = ({ fileId }: ChatWrapperProps) => { const { data, isLoading } = trpc.getFileUploadStatus.use ...

Incorporating tawk.to into a Nuxt/Vue application

Has anyone had success implementing tawk.to in a Nuxt application? I took the initiative to create a file called "tawk.js" in my plugin folder and added the following code: var Tawk_API = Tawk_API || {}, Tawk_LoadStart = new Date() (function () { ...

Dynamic fields in Django ImportExport

I am currently utilizing Django's ImportExport feature. My goal is to export all entries from a model named Room. Each Room can contain anywhere from one to a maximum of 20 Tables. For this purpose, I have created the following resource: class RoomRe ...

What is the best way to showcase the output of a Perl script on a webpage

I recently came across a resource discussing the process of executing a perl script from a webpage. What is the best way to run a perl script from a webpage? However, I am facing a situation where the script I have takes more than 30 seconds to run and d ...