Django ChartJS Bar Chart Example Tutorial

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


Hi Dev,

Are you looking for example of django chartjs bar chart example. I explained simply step by step how to use chartjs bar chart in django. We will look at example of chartjs bar chart in django. you can understand a concept of django chartjs bar chart tutorial. you will do the following things for chartjs bar chart in django example.

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 manage.py startapp chart
Step 3 : Update setting.py

In this step we require to do two things in our settings.py 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 settings.py file:

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

....
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'chart',
]
Step 4 : Database Setup

Next step, we will modify the settings.py file and update the database settings to configure the mydb database:

settings.py
DATABASES = {  
    'default': {  
        'ENGINE': 'django.db.backends.mysql',  
        'NAME': 'example',  
        'USER':'root',  
        'PASSWORD':'root',  
        'HOST':'localhost',  
        'PORT':'3306'  
    }  
}  
Step 5: Create a Model

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

cropper/models.py
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.name, self.num_users) 

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

Step 6 : Create a Migrations
python manage.py makemigrations

After successfully run the above command go to the cropper/migrations/0001_initial.py

cropper/migrations/0001_initial.py
# 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 = [
        migrations.CreateModel(
            name='Editor',
            fields=[
                ('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 manage.py 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/views.py file and add:

chart/views.py
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:

chart/templates/base.html
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js" integrity="sha256-Uv9BNBucvCPipKQ2NS9wYpJmi8DTOEfTA/nH2aoJALw=" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.css" integrity="sha256-aa0xaJgmK/X74WM224KMQeNQC2xYKwlAt08oZqjeF0E=" crossorigin="anonymous" />
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <title>Django ChartJS Chart Example</title>
</head>
<body>
    <h1 style="text-align: center;margin-top:70px;">Django ChartJS Bar Chart Example - Tuts-Station.com</h1>
    <canvas id="myChart" width="400" height="100" style="margin-top:50px;"></canvas>
</body>
<script>

$(document).ready(function(){
    var ctx = document.getElementById('myChart').getContext('2d');
    var myChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: [{%for data in qs%}'{{data.name}}',{%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
                }
            }
        }
    });
});

</script>
</html>
Step 9 : Creating URLs

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

chart/urls.py
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 urls.py your root preoject folder lets update the file.

example/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    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 manage.py runserver

Next, go to the address with a web browser.

http://localhost:8000/chart/

I Hope It will help you....