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:
from django.db import models
class Sale(models.Model):
amount = models.FloatField()
product_name = models.CharField(max_length=40)
created_time = models.DateTimeField()
updated_time = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = 'sale'
verbose_name_plural = 'sales'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:
To do this, We add a function to our model to extract the data:
Step #2 - Create View
In view.py, we just need to call this function and create the structure needed for the chart. As follows:
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:
In this example, I used Morris.Bar Chart to display the information.
Last updated
Was this helpful?