[Chartjs]-ChartJS : It's not showing in html on Django

3👍

Your code seems to work fine. Here is a jsfiddle using your data.

So probably you need to write the array in the template as json like {{ top5StockCode|safe }} and {{top5TotalSales|safe}}

so your final code should be:

<div class="top5">
    <p class="topicTop5">Top 5 Selling Products</p>
    <canvas id="top5"></canvas>
</div>
<script>
    var top5 = document.getElementById('top5').getContext('2d');
    var chart = new Chart(top5, {
        type: 'horizontalBar',
        data: {
            labels: {{top5StockCode|safe}},
            datasets: [{
                label: 'Top 5 selling products ',
                backgroundColor: '#CE3B21',
                borderColor: 'rgb(255, 99, 132)',
                data: {{top5TotalSales|safe}}
            }]
        },
        options: {   
            legend: { 
                display: false
            },
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                yAxes: [{
                    ticks: {
                         beginAtZero:true
                    }
                }]
            }
        }
    });
</script>

0👍

I think you forgot to include the library

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

Try This code

<div class="top5">
    <p class="topicTop5">Top 5 Selling Products</p>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
    <canvas id="top5"></canvas>
</div>
<script>
    var top5 = document.getElementById('top5').getContext('2d');
    var chart = new Chart(top5, {
        type: 'horizontalBar',
        data: {
            labels: {{top5StockCode|safe}},
            datasets: [{
                label: 'Top 5 selling products ',
                backgroundColor: '#CE3B21',
                borderColor: 'rgb(255, 99, 132)',
                data: {{top5TotalSales|safe}}
            }]
        },
        options: {   
            legend: { 
                display: false
            },
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                yAxes: [{
                    ticks: {
                         beginAtZero:true
                    }
                }]
            }
        }
    });
</script>

Leave a comment