Cant pass data to Chart.js with Django

40 views Asked by At

Im using bootstrap template for my website and have problem to pass data from view in django to html to chart.js

I tried to pass data like any other variable but it didnt worked. I cant see data

I have 2 charts one (pie) with predefined data set and second (doughnut) i want to pass data from view, neither shows after render.

What do i do wrong?

View.py

        ctx = {
            "tournament": tournament,
            "pairing": pairing,
            "players_points": players_points,
            "army_points": army_points,
            "teamB": teamB,
            "form": form,
            "green": green,
            "yellow": yellow,
            "red": red,
            "green_p": green_p,
            "yellow_p": yellow_p,
            "red_p": red_p,
            "total": total,
            # "chart_data": chart_data,
            "chart_data": json.dumps(chart_data),
        }
        return render(request, "pairing5v5.html", ctx)

html

        <div class="container-fluid pt-4 px-4">
            <div class="row g-4">
                <div class="col-sm-12 col-xl-6">
                    <div class="bg-secondary rounded h-100 p-4">
                        <h6 class="mb-4">Pie Chart</h6>
                        <canvas id="pie-chart" width="500" height="500"></canvas>
                    </div>
                </div>
                <div class="col-sm-12 col-xl-6">
                    <div class="bg-secondary rounded h-100 p-4">
                        <h6 class="mb-4">Doughnut Chart - {{ chart_data|safe }}</h6>
                        <canvas id="doughnut-chart"></canvas>
                    </div>
                </div>
            </div>
        </div>

main.js

    // Pie Chart
    var ctx5 = $("#pie-chart").get(0).getContext("2d");
    var myChart5 = new Chart(ctx5, {
        type: "pie",
        data: {
            labels: ["Italy", "France", "Spain", "USA", "Argentina"],
            datasets: [{
                backgroundColor: [
                    "rgba(235, 22, 22, .7)",
                    "rgba(235, 22, 22, .6)",
                    "rgba(235, 22, 22, .5)",
                    "rgba(235, 22, 22, .4)",
                    "rgba(235, 22, 22, .3)"
                ],
                data: [55, 49, 44, 24, 15]
            }]
        },
        options: {
            responsive: true
        }
    });

    // Doughnut Chart
    var ctx6 = $("#doughnut-chart").get(0).getContext("2d");
    var myChart6 = new Chart(ctx6, {
        type: "doughnut",
        data: {
            labels: ["Green", "Yellow", "Red"],
            datasets: [{
                backgroundColor: [
                    "rgba(235, 22, 22, .7)",
                    "rgba(235, 22, 22, .6)",
                    "rgba(235, 22, 22, .5)",
                ],
                data: {{ chart_data|safe }}
            }]
        },
        options: {
            responsive: true
        }
    });
0

There are 0 answers