Django ChartJS Chart Example Tutorial

Published On: 08/08/2022 | Category: Django

Hi Dev,

This article is focused on django chartjs. We will look at example of django chartjs ajax example. step by step explain how to create chart in django. I would like to share with you how to use chartjs in django.

Chartjs is a js library, this library through we can use bar chart, line chart, area chart, column chart, etc. chartjs is a open-source chart library. chartjs also provide several theme and graph that way you can use more chart from here : chartjs Site.

you can simply use Line Charts, Bar Charts, Pie Charts, Area Charts, etc using chartjs js.

In this example, we will create some dummy users records and then we will display a line chart with all months of current years. so let's follow the below step and add a chart in your django app.

Step 1 : Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example
Step 2 : Create a App
python3 startapp chart
Step 3 : Update

In this step we require to do two things in our file, One is to change the path of template look up directory. Second one is to configure our media folder. Add the below lines to your file:

Next, you need to add it in the file as follows:

Step 4 : Database Setup

Next step, we will modify the file and update the database settings to configure the mydb database:
    'default': {  
        'ENGINE': 'django.db.backends.mysql',  
        'NAME': 'example',  
Step 5: Create a Model

In this step we will require the database model for storing contacts.Open the cropper/ file and add the following code:

from django.db import models

# Create your models here.
class Editor(models.Model):
    name = models.CharField(max_length=200)
    num_users = models.IntegerField()

    def __str__(self):
        return "{}-{}".format(, self.num_users) 

After creating these model, you need to create migrations using the following command:

Step 6 : Create a Migrations
python makemigrations

After successfully run the above command go to the cropper/migrations/

# Generated by Django 3.1.7 on 2022-07-25 11:13

from django.db import migrations, models

class Migration(migrations.Migration):

    initial = True

    dependencies = [

    operations = [
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=200)),
                ('num_users', models.IntegerField()),

Next, you need to migrate your database using the following command:

python migrate
Step 7 : Creating the Views

In this step, we need to create the views for performing fetch record to the database.Open the chart/ file and add:

from django.shortcuts import render
from django.views.generic import TemplateView
from .models import Editor

# Create your views here.
class EditorChartView(TemplateView):
    template_name = 'chart.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["qs"] = Editor.objects.all()
        return context
Step 8 : Creating the Templates

Here, in this step we need to create a new folder named charts in the templates folder of charts.

Next, open the chart/templates/base.html file and the add:

<!doctype html>
<html lang="en">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <script src="" integrity="sha256-Uv9BNBucvCPipKQ2NS9wYpJmi8DTOEfTA/nH2aoJALw=" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="" integrity="sha256-aa0xaJgmK/X74WM224KMQeNQC2xYKwlAt08oZqjeF0E=" crossorigin="anonymous" />
    <script src=""></script>
    <title>Django ChartJS Chart Example</title>
    <h1 style="text-align: center;margin-top:70px;">Django ChartJS Chart Example -</h1>
    <canvas id="myChart" width="400" height="100" style="margin-top:50px;"></canvas>

    var ctx = document.getElementById('myChart').getContext('2d');
    var myChart = new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: [{%for data in qs%}'{{}}',{%endfor%}],
            datasets: [{
                label: '# of users',
                data: [{%for data in qs%}{{data.num_users}},{%endfor%}],
                backgroundColor: [
                    'rgba(255, 99, 132, 0.2)', 
                    'rgba(54, 162, 235, 0.2)',
                    'rgba(255, 206, 86, 0.2)',
                    'rgba(75, 192, 192, 0.2)',
                    'rgba(153, 102, 255, 0.2)',
                    'rgba(255, 159, 64, 0.2)'
                borderColor: [
                    'rgba(255, 99, 132, 1)',
                    'rgba(54, 162, 235, 1)',
                    'rgba(255, 206, 86, 1)',
                    'rgba(75, 192, 192, 1)',
                    'rgba(153, 102, 255, 1)',
                    'rgba(255, 159, 64, 1)'
                borderWidth: 1
        options: {
            scales: {
                y: {
                    beginAtZero: true

Step 9 : Creating URLs

In this section, we’ll create the urls to access our views.Go to the chart/ file and update it as follows:

from django.urls import path
from chart.views import EditorChartView

urlpatterns = [
    path('chart/', EditorChartView.as_view(), name='editorChart'),

Next, we will require the modify the your root preoject folder lets update the file.

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

urlpatterns = [
    path('', include('chart.urls')),
Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python runserver

Next, go to the address with a web browser.


I Hope It will help you....