In this tutorial we are going to explore a little bit of how to make Django talk with Chart.js and render some simple charts based on data extracted from our models.
Installation
For this tutorial all you are going to do is add the Chart.js lib to your HTML page:
You can
download it from Chart.js official website and use it locally, or you can use it from a CDN using the URL above.
Example Scenario
I’m going to use the same example I used for the tutorial How to Create Group By Queries With Django ORM which is a good complement to this tutorial
because actually the tricky part of working with charts is to transform the data so it can fit in a bar chart / line chart / etc.
We are going to use the two models below, Country and City:
For the first example we are only going to retrieve the top 5 most populous cities and render it as a pie chart. In this strategy we are going to return the chart data as part of the view context and inject the results in the JavaScript code using the Django Template language.
Basically in the view above we are iterating through the
City queryset and building a list of labels and a list of data. Here in this case the data is the population count saved in the City model.
In the example above the base.html template is not important but you can see it in the code example I shared in the end of this post.
This strategy is not ideal but works fine. The bad thing is that we are using the Django Template Language to interfere with the JavaScript logic. When we put {{data|safe}} we are injecting a variable that came from the server directly in the JavaScript code.
The code above looks like this:
Example 2: Bar Chart with Ajax
As the title says, we are now going to render a bar chart using an async call.
So here we are using two views. The home view would be the main page where the chart would be loaded at. The other view population_chart would be the one with the sole responsibility to
aggregate the data the return a JSON response with the labels and data.
If you are wondering about what this queryset is doing, it is grouping the cities by the country and aggregating the total population of each country. The result is going to be a list of country + total population. To learn more about this kind of query have a look on this post: How to Create Group By
Queries With Django ORM
$(function(){var$populationChart=$("#population-chart");$.ajax({url:$populationChart.data("url"),success:function(data){varctx=$populationChart[0].getContext("2d");newChart(ctx,{type:'bar',data:{labels:data.labels,datasets:[{label:'Population',backgroundColor:'blue',data:data.data}]},options:{responsive:true,legend:{position:'top',},title:{display:true,text:'Population Bar Chart'}}});}});});{%endblock%}
Now we have a better separation of concerns. Looking at the chart container:
We added a reference to the URL that holds the chart rendering logic. Later on we are using it to execute the Ajax call.
Inside the success callback we then finally execute the Chart.js related code using the
JsonResponse data.
Conclusions
I hope this tutorial helped you to get started with working with charts using Chart.js. I published another tutorial on the same subject a while ago but using the Highcharts library. The approach is pretty much the same:
How to Integrate Highcharts.js with Django.
If you want to grab the code I used in this tutorial you can find it here: github.com/sibtc/django-chartjs-example.