Chartjs-How to implement chart.js in Django?

4👍

All that chart.js cares about is a list of labels, and a list of values. So you’ll have to somehow provide it with that. Your lineChart view function responds with a list of labels and a list of datapoints so it suits our needs exactly. What you’ll need to do is have your web page send a request to your django server to request the data it should display. When a response is received, you can feed in your data to chart.js and build your chart. Here’s a stripped-down code of how all of this fits together from the client’s side and from the server’s side:

Server Side

def lineChart(request):    
    return JsonResponse(data = {
        'labels': ["Red Label", "Yellow Label"],
        'data': [5, 6],
    })

Client Side

<canvas id="chart"></canvas>
<script>
  let ctx = document.getElementById('chart');
  $.ajax({
    url: '/lineChart/',
    success: function(response){
      new Chart(ctx, {
        type: 'line',
        data: {
          labels: response.labels,
          datasets: [{
            data: response.data
          }]
        }
      });
    }
  });
</script>

One thing I should point out are the different languages we are dealing with here and how they interact. Django renders an HTML page. During this rendering process, it has access to python variables called context variables. After it’s done rendering, it sends that final HTML page to the client. On the client’s side is chart.js which is a JavaScript library, it needs JavaScript variables to work with. So using Django’s context variables wouldn’t really work. …unless… you use django to render its context variables into the html page as hard-coded javascript-vaild values. I’m guilty of doing this in the past but I would not recommend this approach. It smells awful!

Leave a comment