Chart.js is a cool open source JavaScript library that helps you render HTML5 charts. It is responsive and counts with 8 different chart types. 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. InstallationFor 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 ScenarioI’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,
And the raw data stored in the database:
Example 1: Pie ChartFor 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. views.py
Basically in the view above we are iterating through the
For the urls.py
Now the template. I got a basic snippet from the Chart.js Pie Chart Documentation. pie_chart.html
In the example above the 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 The code above looks like this: Example 2: Bar Chart with AjaxAs the title says, we are now going to render a bar chart using an async call. views.py
So here we are using two views. The 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 urls.py
home.html
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 ConclusionsI 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. |