How to use Chart JS in Django

Learn how to use the chart JS in Django. In this tutorial, you will learn how to use the Chart JS in Django with the dynamic data in the database. In this, we will pass the query set data to the HTML page context by converting it into a Data Frame. And this will let you access the dynamic content in visualization for Charts. Dynamic Data Visualization in Django.

Requirements :

pip install django

This command will install the latest Django package into your local machine.

Firstly Create a Django Project :

python -admin django startproject project

This command will create new project.

Navigate to Project folder :

cd project #projectname 

This will change the current directory of the terminal to the project directory

Secondly Creating app with Demo app :

py startapp demo

Create a demo app for the Django project we have created.

Thirdly Create in Demo app

from django.urls import path
from . import views
urlpatterns = [
    path('', views.home, name="home")

Here, We are creating the routing paths for the home view this will render out the Html page we have created for the model form. However the ” will represent the localhost path it will render the Html template as the homepage for the project on the localhost address. i.e.

To get chart js cdn and sample script Chartjs

Create Student Model :

from django.db import models
class Student(models.Model):
       name = models.CharField(max_length=200)
       roll = models.IntegrField()

In this step, we are creating a model with the name of the Student with the two fields that are name and rank. However, the name is character field this will create a column with the name under the student table. And the roll is an integer field this will also create a new column under the Student table in the Database.

Main (include demo URLs) :

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('', include('demo.urls'))

Configure the demo app URLs to main URLs by using the include function this will render the demo app paths as well along with the admin paths which are configured above

Apply Model Table Migrations :

py makemigrations
py migrate 

These commands will detect the changes in the file and hence create the new models. The second command as well also related to the model table which will migrate the tables to the database we have configured

Create a view :

from django.shortcuts import render
from .models import *
import pandas as pd
def home(request):
     item = Student.objects.all().values()
     mydict = {
     return render(request, 'index.html',context=mydict)

In this view we are importing an external library which is pandas using this library we can achieve the required functionalises required for us. Create a view with name home next item is the instance which hold all the values into the Student tables. Next we are using the Data frame concept to convert the query-set of Student table into the data frame. Now convert the name and roll column into the list of values. Pass the lists into the context of index html template.

Html Code for Dynamic Charts :

<canvas id="myChart" width="400" height="400"></canvas>
var df ={{df|safe}}
var df1 ={{df1|safe}}
<script> var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, {
             type: 'bar',
             data: {labels: df1,         
             datasets: [{
             label: '# of Votes',             
             data: df,            

However, We have passed the lists of values of name and roll columns. Now assign the list variables to the javascript variables and then use them in jinja format. i.e. We are assigning the variable df to the data nothing but the list of values in the roll column. And the df1 to the labels set which will give us the names column values.

Output :