How to Integrate Highcharts.js in Django ?

Published On: 21/07/2022 | Category: Django Python


Hi Dev,

Today, I will let you know example of django highcharts example. you will learn how to integrate highcharts.js with django. This article goes in detailed on create charts in django using database. you can understand a concept of how to integrate highcharts js with django template. So, let's follow few step to create example of how to use highcharts with django.

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

So, we will use in titanic dataset in tis tutorial and count how many survived or not base on ticket class.

You can simply use Line Charts, Bar Charts, Pie Charts, Area Charts etc.

Here i explained simply step by step example of here you will learn django Highcharts example tutorial.

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:

import os

....
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 click and visitors data.Open the chart/models.py file and add the following code:

chart/models.py
from django.db import models

class Passenger(models.Model):
    name = models.CharField(max_length=255)
    sex = models.CharField(max_length=255)
    survived = models.BooleanField()
    age = models.FloatField()
    ticket_class = models.PositiveSmallIntegerField()
    embarked = models.CharField(max_length=255)

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 chart/migrations/0001_initial.py

chart/migrations/0001_initial.py
# Generated by Django 3.1.7 on 2022-07-20 11:58

from django.db import migrations, models


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Passenger',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=255)),
                ('sex', models.CharField(max_length=255)),
                ('survived', models.BooleanField()),
                ('age', models.FloatField()),
                ('ticket_class', models.PositiveSmallIntegerField()),
                ('embarked', models.CharField(max_length=255)),
            ],
        ),
    ]

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.conf import settings
from .models import Passenger
from django.db.models import Count, Q
import datetime
from django.db.models import Count

# Create your views here.

def ticket_class_view(request):
    dataset = Passenger.objects \
        .values('ticket_class') \
        .annotate(survived_count=Count('ticket_class', filter=Q(survived=True)),
                  not_survived_count=Count('ticket_class', filter=Q(survived=False))) \
        .order_by('ticket_class')
    return render(request, 'member.html', {'dataset': dataset})
Step 8 : Creating the Templates

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Django Highcharts Example - Tuts-Station.com</title>
</head>
<body>
    <h1>Django Highcharts Js example - Tuts-Station.com</h1>
    <div id="container"></div>
    <script src="https://code.highcharts.com/highcharts.src.js"></script>
    <script>
      Highcharts.chart('container', {
          chart: {
              type: 'column'
          },
          title: {
              text: 'Titanic Survivors by Ticket Class'
          },
          xAxis: {
              categories: [
                {% for entry in dataset %}'{{ entry.ticket_class }} Class'{% if not forloop.last %}, {% endif %}{% endfor %}
              ]
          },
          series: [{
              name: 'Survived',
              data: [
                {% for entry in dataset %}{{ entry.survived_count }}{% if not forloop.last %}, {% endif %}{% endfor %}
              ],
              color: 'blue'
          }, {
              name: 'Not survived',
              data: [
                {% for entry in dataset %}{{ entry.not_survived_count }}{% if not forloop.last %}, {% endif %}{% endfor %}
              ],
              color: 'red'
          }]
      });
    </script>
</body>
</html>
Step 9 : Creating URLs

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

chart/urls.py
from django.urls import path
from .views import ticket_class_view

urlpatterns = [
    path('charts/', ticket_class_view, name="ticket_class_view"),
]

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

Here, we need to add some dummy records on passengers table as like bellow screen shot:



Next, go to the http://localhost:8000/charts address with a web browser.

I Hope It will help you....