Django ChartJS Line Chart Example Tutorial

Published On: 25/03/2025 | Category: Django
Django ChartJS Line Chart Example

Hello Django Developers 👋,

Today, we will explore how to integrate Chart.js with Django to create a dynamic Line Chart. This guide is perfect for those looking to visualize data directly within their Django web apps using beautiful, interactive charts.

This article provides a complete tutorial for building a line chart with ChartJS using Django, from creating models to rendering data dynamically in templates. ChartJS is a powerful, open-source JavaScript library for building charts like bar, line, pie, and more. You can explore its features from the official Chart.js documentation.

Let’s get started with this step-by-step Django ChartJS tutorial 👇

Step 1 : Create a Project

django-admin startproject example

Step 2 : Create a App

python3 manage.py startapp chart

Step 3 : Update settings.py

Include your app in INSTALLED_APPS like this:

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

DATABASES = {  
    'default': {  
        'ENGINE': 'django.db.backends.mysql',  
        'NAME': 'example',  
        'USER':'root',  
        'PASSWORD':'root',  
        'HOST':'localhost',  
        'PORT':'3306'  
    }  
}  

Step 5 : Create a Model

from django.db import models

class Editor(models.Model):
    name = models.CharField(max_length=200)
    num_users = models.IntegerField()

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

Step 6 : Create a Migrations

python manage.py makemigrations
python manage.py migrate

Step 7 : Creating the Views

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

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

Create chart/templates/base.html and add:

<!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"></script>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <title>Django ChartJS Line Chart Example</title>
</head>
<body>
    <h1 style="text-align:center; margin-top:50px;">Django ChartJS Line Chart - Stuffcoder.com</h1>
    <canvas id="myChart" width="400" height="100"></canvas>

    <script>
    $(document).ready(function(){
        var ctx = document.getElementById('myChart').getContext('2d');
        var myChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: [{% for data in qs %}'{{ data.name }}',{% endfor %}],
                datasets: [{
                    label: '# of Users',
                    data: [{% for data in qs %}{{ data.num_users }},{% endfor %}],
                    backgroundColor: 'rgba(54, 162, 235, 0.2)',
                    borderColor: 'rgba(54, 162, 235, 1)',
                    borderWidth: 2,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                scales: {
                    yAxes: [{
                        ticks: {
                            beginAtZero: true
                        }
                    }]
                }
            }
        });
    });
    </script>
</body>
</html>

Step 9 : Creating URLs

chart/urls.py

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

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

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

python manage.py runserver
http://localhost:8000/chart/

🎉 That’s it! You now have a working ChartJS Line Chart integrated in your Django application.

Happy Charting with Django and ChartJS! 📊

Top SEO Keywords:
django chartjs tutorial, chartjs line chart in django, django chart examples, django chartjs integration, line chart django chart.js, django chart rendering, chart js django step by step, how to use chart.js in django, django visualize data chart, django line graph chartjs

Frequently Asked Questions (FAQs)

1. What is ChartJS used for in Django?

ChartJS is a JavaScript library used to create beautiful, responsive charts. In Django, it helps visualize data from models in graphical format.

2. How to pass data from Django models to ChartJS?

You can pass data to templates using Django views and render them inside ChartJS script blocks using template tags.

3. Can I create multiple chart types with ChartJS in Django?

Yes, ChartJS supports multiple chart types such as line, bar, pie, doughnut, radar, and area charts.

4. Is ChartJS free to use in Django projects?

Yes, ChartJS is open-source and free to use under the MIT license.

5. Why is my ChartJS chart not displaying in Django?

Make sure the script is correctly referencing your data and ChartJS is properly included. Also verify no template tag syntax issues.