If you wish to show charts in your Django internet software, whether or not it’s a bar chart, a pie chart, or different charts, you may have so many choices at your disposal — from utilizing Plotly in Python language to utilizing HighCharts.js
or Charts.js
in JavaScript.

The fantastic thing about utilizing the later over the previous is that every one the heavy lifting has been carried out for us. By putting the hyperlink in your template, you’ll be able to make the most of all of the out there options. We have already demonstrated tips on how to show charts utilizing Highcharts.js
in a Django internet software.
On this tutorial, we’ll take note of Charts.js
. Particularly, we’ll be taught:
- One other option to populate the database apart from those talked about whereas studying how to take action with
Highcharts.js
- Tips on how to question the database to show the information structured in such a method that
Charts.js
can perceive. - Tips on how to show each bar chart and pie chart
The Mannequin
For this venture, we’ll use the information from Kaggle1 that reveals the richest individuals on this planet as of 2022. The info comprises a number of columns however we’re solely fascinated with only a few of them. Allow us to create a database mannequin for the dataset.
from django.db import fashions GENDER = ( ('M', 'Male'), ('F', 'Feminine'), ) class Richest(fashions.Mannequin): identify = fashions.CharField(max_length=100) gender = fashions.CharField(max_length=1, selections=GENDER) net_worth = fashions.IntegerField() nation = fashions.CharField(max_length=100) supply = fashions.CharField(max_length=100) def __str__(self): return self.identify
The mannequin comprises names of the richest individuals on this planet, their web value, nation of origin and their supply of wealth.

Populating the database
Within the earlier tutorial venture on making a chart utilizing Highcharts.js
, I confirmed you one of many methods to populate a database. I wrote a script from the Django shell to populate the database. On this tutorial, we’ll be taught a distinct technique.
We’ll use Django’s BaseCommand
class to create a customized administration command that populates the database utilizing the dataset.
Begin by creating new folders contained in the app folder. For instance, assuming the identify of your Django app is charts and is created in your present listing, run the next in your Ubuntu terminal:
mkdir charts/administration/instructions -p
The p
flag makes it doable to create a nested folder in a single command. Contained in the instructions
folder, create a brand new file named populate_db.py
:
nano charts/administration/instructions/populate_db.py
let’s first import the required modules:
from django.core.administration.base import BaseCommand from charts.fashions import Richest import csv import math
BaseCommand
is a category offered by Django that serves as the bottom class for writing customized administration instructions. Administration instructions are scripts that may be run from the command line to carry out numerous duties associated to your Django app.
The BaseCommand
class supplies a number of helpful strategies and attributes that make it simple to jot down customized administration instructions. Whenever you create a customized administration command by subclassing BaseCommand
, you want to override the deal with
technique to outline the conduct of your command.
The deal with
technique is named when the command is executed, and it receives any command-line arguments handed to the command as key phrase arguments.
Along with the deal with
technique, the BaseCommand
class supplies a number of different strategies and attributes that you should utilize when writing customized administration instructions.
For instance, as we will see, you should utilize the add_arguments
technique to outline customized command-line arguments to your command, and you should utilize the stdout
and stderr
attributes to jot down output to the Ubuntu terminal.
class Command(BaseCommand): assist = 'Populate the database utilizing a CSV file' def add_arguments(self, parser): parser.add_argument('forbes_2022_billionaires.csv', kind=str, assist='The trail to the CSV file') def deal with(self, *args, **choices): csv_file = choices['forbes_2022_billionaires.csv'] with open(csv_file, 'r') as f: reader = csv.DictReader(f) for row in reader: skip_row = False for worth in row.values(): attempt: if math.isnan(float(worth)): skip_row = True break besides ValueError: move if skip_row: proceed net_worth = int(float(row['finalWorth'])) obj, created = Richest.objects.get_or_create( identify=row['personName'], gender=row['gender'], net_worth=net_worth, nation=row['countryOfCitizenship'], supply=row['source'] ) self.stdout.write(self.fashion.SUCCESS('Efficiently populated the database'))
We outline a brand new Command
class that inherits from BaseCommand
.
Within the add_arguments
technique, we outline a brand new command-line argument referred to as csv_file
that specifies the trail to the CSV file. Within the deal with
technique, we learn the information from the CSV file and use a conditional assertion to verify if any of the values within the present row are NaN.
If any worth is NaN, we use the proceed
assertion to skip this row and transfer on to the subsequent one. In any other case, we use the get_or_create
technique so as to add the information to the database. Lastly, we use the self.stdout.write
technique to print successful message.
We use a nested loop to iterate over every worth within the row. For every worth, we use a try-except block to attempt to convert the worth to a float and verify whether it is NaN. If a ValueError
exception happens, we catch it and ignore it utilizing the move
assertion.
If any worth within the row is NaN, we set the skip_row
variable to True
and use the break
assertion to exit the interior loop. After the interior loop completes, we use an if assertion to verify if the skip_row
variable is True
. Whether it is, we use the proceed
assertion to skip this row and transfer on to the subsequent one.
Nevertheless, an issue arises from the dataset. The net_worth
discipline is an IntegerField
. Whereas, the information kind of the finalWorth
column is float. To keep away from errors, we first convert the worth of the net_worth
discipline within the present row to a float utilizing the float
perform, after which convert it to an integer utilizing the int
perform. We then assign this integer worth to the net_worth
discipline of the Richest
mannequin occasion utilizing the get_or_create
technique.
Be sure to have the forbes_2022_billionaires.csv
file downloaded and positioned in your present listing. Then, run the command we outlined from the command line utilizing the handle.py
script like this:
python3 handle.py populate_db forbes_2022_billionaires.csv
Afterward, successful message will probably be displayed. We have now populated our database. Open the admin interface to see it.

Displaying charts utilizing Charts.js
Be sure to have included the Charts.js
library in your template by including the next script tag to the <head>
part of your HTML file:
<script src="https://cdn.jsdelivr.web/npm/chart.js"></script>
Subsequent, add a <canvas>
aspect to your template the place you wish to show the chart. Give this aspect an id so you’ll be able to reference it in your JavaScript code.
Right here’s an instance:
<canvas id="myChart"></canvas>
On this demonstration, we’ll question the database to:
- Calculate complete web value of every nation
- Get the highest 10 richest individuals on this planet
- Get the highest 10 richest girls on this planet
- Get the distribution of wealth by gender
We can even embody a pie chart. You’ll be able to all the time verify the supply code for extra particulars.
Displaying the full web value of every nation
from django.shortcuts import render from django.db.fashions import Sum from .fashions import Richest def TotalNetWorth(request): # Question the database to get the information information = Richest.objects.values('nation').annotate(total_net_worth=Sum('net_worth')).order_by('-total_net_worth') # Put together the information for the chart chart_data = [] for merchandise in information: chart_data.append({ 'nation': merchandise['country'], 'total_net_worth': merchandise['total_net_worth'] }) # Render the template with the chart information return render(request, 'total_net_worth.html', {'chart_data': chart_data})
We group the information by nation utilizing the values
technique, and utilizing the annotate
technique, we calculate the full web value of every nation.
Subsequent, we put together the information for the chart by creating a brand new listing referred to as chart_data
and appending a dictionary for every merchandise within the question outcome.
Every dictionary comprises two keys: 'nation'
and 'total_net_worth'
, which signify the nation and its complete web value, respectively.
<script> var ctx = doc.getElementById('myChart').getContext('second'); var chart = new Chart(ctx, { kind: 'bar', information: { labels: {protected }.map(merchandise => merchandise.nation), datasets: [{ label: 'Total Net Worth', data: {safe }.map(item => item.total_net_worth), backgroundColor: 'rgba(54, 162, 235, 0.2)', borderColor: 'rgba(54, 162, 235, 1)', borderWidth: 1 }] }, choices: { scales: { y: { beginAtZero: true } } } }); </script>
Right here, we create a brand new Chart
object and move it the context of the <canvas>
aspect and an choices object that specifies the kind of chart and its information.
We use the chart_data
variable handed as context to populate the chart with information.
Then, we use the map
technique to extract the nation names and complete web value values from the chart_data
and assign them to the labels
and information
properties of the chart’s datasets.

Try the supply code for an illustration of a pie chart. It’s virtually the identical.
Displaying the highest ten richest individuals on this planet
def TopTenRichest(request): # Question the database to get the information information = Richest.objects.order_by('-net_worth')[:10] # Put together the information for the chart chart_data = [] for merchandise in information: chart_data.append({ 'identify': merchandise.identify, 'net_worth': merchandise.net_worth }) # Render the template with the chart information return render(request, 'top_ten_richest.html', {'chart_data': chart_data})

The next code reveals tips on how to show a pie chart utilizing Charts.js
:
var ctx = doc.getElementById('myChart').getContext('second'); var myChart = new Chart(ctx, { kind: 'pie', information: { labels: {protected }.map(merchandise => merchandise.identify), datasets: [{ label: 'Net Worth', data: {safe }.map(item => item.net_worth), backgroundColor: [ 'rgb(255, 99, 132)', 'rgb(54, 162, 235)', 'rgb(255, 205, 86)', 'rgb(75, 192, 192)', 'rgb(153, 102, 255)', 'rgb(255, 159, 64)', 'rgb(255, 99, 132)', 'rgb(54, 162, 235)', 'rgb(255, 205, 86)', 'rgb(75, 192, 192)' ], hoverOffset: 4 }] }, choices: { title: { show: true, textual content: 'High Ten Richest Folks' } } });
This code creates a brand new Chart
object and units its kind to 'pie'
. The info for the chart is taken from the chart_data
variable that was handed to the template from TopTenRichest
view perform.
The labels
for the chart are set to the names of the richest individuals, and the information for the chart is about to their web worths.
The supply code additionally comprises the bar chart instance.
Displaying the highest ten richest girls
def TopRichestWomen(request): information = Richest.objects.filter(gender="F").order_by('-net_worth')[:10] names = [item.name for item in data] net_worths = [item.net_worth for item in data] return render(request, 'top_richest_women.html', { 'names': names, 'net_worths': net_worths })

Distribution of wealth by gender
def WealthByGender(request): # Question the database to get the full web value for every gender male_net_worth = Richest.objects.filter(gender="M").combination(Sum('net_worth'))['net_worth__sum'] female_net_worth = Richest.objects.filter(gender="F").combination(Sum('net_worth'))['net_worth__sum'] # Put together the information for the chart information = { 'labels': ['Male', 'Female'], 'datasets': [{ 'data': [male_net_worth, female_net_worth], 'backgroundColor': ['#36A2EB', '#FF6384'] }] } # Render the chart utilizing the Chart.js library return render(request, 'wealth_by_gender.html', {'information': information})

And that is the pie chart. Verify the supply code for extra particulars:
Conclusion
On this venture tutorial, we’ve discovered numerous methods to question our database, construction the information and displayed them utilizing charts.js
, a JavaScript library for information visualization. We noticed how Django interacts with charts.js
to show charts on a template.
We additionally discovered one other option to populate the database by utilizing Django’s BaseCommand
class. As a result of nature of the dataset, we had been restricted to solely bar and pie charts. Nevertheless, we will apply the method to create different charts.
Use the data you discovered to combine charts in your Django internet software.
✅ Really helpful: The Math of Turning into a Millionaire in 13 Years

Jonathan Okah is an expert freelance Python developer whose main purpose is to resolve a perceived drawback with the usage of expertise, thus making life simple for you.
He has fundamental data of Python, C, JavaScript, HTML, CSS and R, however has taken his data of Python to the subsequent stage at Upwork, the place he performs companies for shoppers.
Jonathan has a aptitude for writing and has written a number of weblog articles for shoppers. He’s continually studying to enhance his expertise. At present, he’s finding out software program engineering, hoping to grow to be a full-stack internet developer.
In his leisure time, Jonathan enjoys enjoying video games and watching the English Premier League. You’ll be able to contact him to your freelance tasks at Upwork.