Django Chart Example
How To showcase information in Django
To display data on a chart, you must extract data from your model or anywhere else and send it to the JS function as JSON. For example, I did this through the following work flow:
​
Step #1 - Make a Model
I want to show my product sales report on the Chart. To do this, I created a model with the following structure in models.py:
1
from django.db import models
2
​
3
​
4
class Sale(models.Model):
5
amount = models.FloatField()
6
product_name = models.CharField(max_length=40)
7
created_time = models.DateTimeField()
8
updated_time = models.DateTimeField(auto_now=True)
9
​
10
class Meta:
11
verbose_name = 'sale'
12
verbose_name_plural = 'sales'
Copied!
​
Import Data
I used django-import-export package to add data through csv, xls, and etc.
​
Extract Data
In this part, I want to display the annual sales information for each product in the chart (By how much of each product has been sold each year) - the structure of data is as follows:
1
# Example
2
data = {
3
'YEAR1': {'PRODUCT_NAME1': 'AMOUNT', 'PRODUCT_NAME2': 'AMOUNT', 'PRODUCT_NAME3': 'AMOUNT'},
4
'YEAR2': {'PRODUCT_NAME1': 'AMOUNT', 'PRODUCT_NAME2': 'AMOUNT', 'PRODUCT_NAME3': 'AMOUNT'},
5
'YEAR3': {'PRODUCT_NAME1': 'AMOUNT', 'PRODUCT_NAME2': 'AMOUNT', 'PRODUCT_NAME3': 'AMOUNT'},
6
}
Copied!
To do this, We add a function to our model to extract the data:
1
from django.db import models
2
from django.db.models import Sum
3
from django.db.models.functions import TruncYear
4
​
5
class Sale(models.Model):
6
...
7
​
8
@classmethod
9
def get_sales_report(cls):
10
annotates = {'total_amount': Sum('amount')}
11
​
12
sales = cls.objects.annotate(
13
year=TruncYear('created_time')
14
).values('product_name', 'year').order_by().annotate(**annotates)
15
​
16
data = {}
17
for sale in sales: # This loop is for building data structures.
18
if sale['year'].year not in data:
19
data[sale['year'].year] = {}
20
​
21
data[sale['year'].year][sale['product_name']] = sale['total_amount']
22
​
23
# The labels are our product names. these gonna be shown in the chart
24
labels = list(sales.values_list('product_name', flat=True).distinct())
25
return data, labels
Copied!
​
Step #2 - Create View
In view.py, we just need to call this function and create the structure needed for the chart. As follows:
1
import json
2
from django.shortcuts import render
3
from app.models import Sale
4
​
5
​
6
def index(request):
7
context = {'segment': 'index'}
8
​
9
sales, labels = Sale.get_sales_report()
10
​
11
# We need to change the data based on how it is displayed on the chart.
12
data = [
13
{
14
'y': year,
15
'a': '{:.2f}'.format(sales[year].get('A')),
16
'b': '{:.2f}'.format(sales[year].get('B')),
17
'c': '{:.2f}'.format(sales[year].get('C'))
18
} for year in sales
19
]
20
​
21
# This is the structure of our chart, And it must be in JSON to be displayed in JS function.
22
context['chart_data'] = json.dumps({
23
'element': 'morris-bar-chart',
24
'data': data,
25
'xkey': 'y',
26
'barSizeRatio': 0.70,
27
'barGap': 3,
28
'resize': True,
29
'responsive': True,
30
'ykeys': ['a', 'b', 'c'], # it can be custom
31
'labels': labels,
32
'barColors': ['0-#1de9b6-#1dc4e9', '0-#899FD4-#A389D4', '#04a9f5'] # it can be custom
33
})
34
​
35
return render(request, 'YOUR_TEMPLATE', context)
Copied!
This is the structure of our chart, And it must be in JSON to be displayed in JS function.

​

Step #3 - Show in Template
In your template, just call your chart and send the data to JS Function. For example:
1
{% load static %}
2
​
3
<div class="col-xl-12">
4
<div class="card">
5
<div class="card-header">
6
<h5>Products Sales Report</h5>
7
</div>
8
<div class="card-block">
9
<div id="morris-bar-chart" style="height:300px"></div>
10
</div>
11
</div>
12
</div>
13
​
14
...
15
​
16
<!-- Load your JS files -->
17
<script src="{% static 'assets/plugins/chart-morris/js/raphael.min.js' %}"></script>
18
<script src="{% static 'assets/plugins/chart-morris/js/morris.min.js' %}"></script>
19
​
20
<script>
21
Morris.Bar({{ chart_data|safe }});
22
</script>
Copied!
In this example, I used Morris.Bar Chart to display the information.
​
Last modified 5mo ago
Copy link
Contents