Home > Software design >  How to plot Django data on a Chart.js graph?
How to plot Django data on a Chart.js graph?

Time:09-29

I am so tilted, so so so tilted. Been trying to work chart.js for a while now on my website I built with Django. I want to plot two fields: Dates and Scores. Dates is a date such as 1/6/2022, score is a float. My issue is that when I pass through the python list to the script it pretends it's something disgusting. But when I copy and past the list and put it into the chart's data it's fine. It only doesn't work when it thinks it's a variable which just makes no sense at all and I can't find anywhere that is talking about this.

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) html that displays the correct chart

<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>

Any help will be sincerely appreciated, this is driving me insane and it's literally the last thing I need to do.

CodePudding user response:

You will need to enclose the context keys with "{{ and }}" while referencing in js. In the html dates and scores needs to updated as "{{dates}}" and "{{scores}}". Make sure to use appropriate tags and filters. You can refer the docs for more info.

  • Related