How to Use Chart.js with Django step by step guide

March 20, 2024


0
4 min read
571

Are you ready to embark on a journey to transform your Django web applications into powerful data visualization platforms? Dive into this comprehensive guide tailored to help you seamlessly integrate Chart.js into your Django projects. Follow along as we explore each step, from setting up your Django environment to creating captivating charts using real-world data, such as country populations, GDP, area, and population density.

Step 1: Setting Up Your Django Project

Let's start by making sure you have Django installed. If not, just run pip install django to get started. Next, start your Django project with the django-admin startproject command, laying the groundwork for your data-driven journey. An example is given below

django-admin startproject chartproject

Step 2: Creating a Django App

Organize your project:

cd chartproject
python manage.py startapp chart_app

Step 3: Defining Models

Define a model for country populations. In chart_app/models.py:

from django.db import models

# Create your models here.
class Country(models.Model):
    name = models.CharField(max_length=100)
    population = models.IntegerField()
    gdp = models.FloatField()
    area = models.FloatField()
    population_density = models.FloatField()

    def __str__(self):
        return self.name

Run migrations:

python manage.py makemigrations
python manage.py migrate

Step 4: Creating a Form

Generate a form to handle user input. In chart_app/forms.py:

from django import forms
from .models import Country

class CountryPopulationForm(forms.ModelForm):
    class Meta:
        model = Country
        fields = ['name', 'population', 'gdp', 'area', 'population_density']

Step 5: Creating Views and Handling Form Submission

Define views to handle form submission and render the chart. In chart_app/views.py:

from django.shortcuts import render
from .forms import CountryPopulationForm
from .models import Country

# Create your views here.

def chart_view(request):
    form = CountryPopulationForm()
    if request.method == 'POST':
        form = CountryPopulationForm(request.POST)
        if form.is_valid():
            form.save()
            form = CountryPopulationForm() #for clear form data
    labels = list(Country.objects.values_list('name', flat=True))
    populations = list(Country.objects.values_list('population', flat=True))
    gdps = list(Country.objects.values_list('gdp', flat=True))
    areas = list(Country.objects.values_list('area', flat=True))
    population_densities = list(Country.objects.values_list('population_density', flat=True))
    return render(request, 'home.html', {'form': form, 'labels': labels, 'populations': populations, 'gdps': gdps, 'areas': areas, 'population_densities': population_densities})

Step 6: Create Templates

We will create a template. To create this, we will create a folder named templates inside the directory of our chart_app. We will name it home.html which we have also mentioned in our views.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>home</title>
</head>
<body>
  
<canvas id="myChart" width="400" height="400"></canvas>

<form method="post">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Submit</button>
</form>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
    var ctx = document.getElementById('myChart').getContext('2d');
    var myChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: {{ labels|safe }},
            datasets: [{
                label: 'Population',
                data: {{ populations|safe }},
                backgroundColor: 'rgba(255, 99, 132, 0.2)',
                borderColor: 'rgba(255, 99, 132, 1)',
                borderWidth: 1
            },{
                label: 'GDP',
                data: {{ gdps|safe }},
                backgroundColor: 'rgba(54, 162, 235, 0.2)',
                borderColor: 'rgba(54, 162, 235, 1)',
                borderWidth: 1
            },{
                label: 'Area',
                data: {{ areas|safe }},
                backgroundColor: 'rgba(255, 206, 86, 0.2)',
                borderColor: 'rgba(255, 206, 86, 1)',
                borderWidth: 1
            },{
                label: 'Population Density',
                data: {{ population_densities|safe }},
                backgroundColor: 'rgba(75, 192, 192, 0.2)',
                borderColor: 'rgba(75, 192, 192, 1)',
                borderWidth: 1
            }]
        },
        options: {
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero: true
                    }
                }]
            }
        }
    });
});
</script>
</body>
</html>

You can adjust it as per your requirement, I have designed it just basic, I am not good at JavaScript, but you can do it as per your requirement.

Step 7: Configure URLs

URLs define the mapping between the web address and the view that should be displayed. To configure URLs, you have to create a file named urls.py in chart_app and add your URLs inside it.

from django.urls import path
from .views import chart_view

urlpatterns = [
    path('', chart_view, name='chart'),
]

You have to include this urls file in your base urls file which you will find in your project's directory.

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('chart_app.urls')),
]

Step 8: Run the Development Server

Finally, you can run the development server by running the following command in your terminal:

python manage.py runserver

Finally, breathe life into your Django project by running your development server. Witness the magic unfold as users interact with your application, dynamically visualizing country data and gaining valuable insights into population trends, GDP distribution, geographical areas, and population densities.

Embrace the power of data visualization today and embark on a transformative journey to unlock actionable insights within your Django web applications. With Chart.js as your trusted ally, you'll captivate your audience and empower them with newfound knowledge and understanding of complex data landscapes. Let your Django projects shine bright as beacons of data-driven innovation!

django Project JavaScript Chart Appreciate you stopping by my post! 😊

Add a comment


Note: If you use these tags, write your text inside the HTML tag.
Login Required
Author's profile
Profile Image

Abdulla Fajal

Django Developer

With 'espere.in' under my care, I, Abdulla Fajal, graciously invite your insights and suggestions, as we endeavour to craft an exquisite online experience together.