Django Dynamic Google Bar Charts Example

Published On: 26/09/2022 | Category: Django


Hi Dev,

If you need to see example of bar chart example using google chart in django python. I explained simply about django dynamic google bar charts example. This article goes in detailed on django dynamic google bar charts example from scratch. This post will give you simple example of django python google bar chart example tutorial.

In this example, we will create a visitors table click, and views column. we will add dummy records every day. Then we fetch and display it in a google bar chart. So you can follow the below step and learn how to use the google bar chart in django.

Here i explained simply step by step example of here you will learn django python google bar chart 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. 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: 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 Visitor(models.Model):
    click = models.IntegerField()
    viewer = models.IntegerField()

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

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

python manage.py makemigrations
python manage.py migrate

Step 5: 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.http import HttpResponse, JsonResponse
from .models import Visitor
import json

# Create your views here.

def googleChart(request):

    #h_var : The title for horizontal axis
    h_var = 'Click'

    #v_var : The title for horizontal axis
    v_var = 'Visitors'

    data = [[h_var,v_var]]
    
    visitors = Visitor.objects.all()

    for visitor in visitors:
        data.append([visitor.click,visitor.viewer])

    h_var_JSON = json.dumps(h_var)

    v_var_JSON = json.dumps(v_var)

    modified_data = json.dumps(data)

    return render(request,"charts.html",{'values':modified_data,\
        'h_title':h_var_JSON,'v_title':v_var_JSON})

Step 6: Creating the Templates

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

<html>
    <head>
    <!--Load the AJAX API-->
        <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
        <script type="text/javascript">
      
            // Load the Visualization API and the corechart package.
            google.charts.load('current', {'packages':['bar']});
      
            // Set a callback to run when the Google Visualization API is loaded.
            google.charts.setOnLoadCallback(drawChart);

            function drawChart() {
            
                //{{values|safe}} : list of list containing points for the chart
                var data = google.visualization.arrayToDataTable({{values|safe}});
            
                // Set chart options
                var options = {
                    title: {{h_title|safe}} +' vs. '+ {{v_title|safe}},
                    hAxis: {title: {{h_title|safe}}},
                    vAxis: {title: {{v_title|safe}}},
                    legend: { position: 'bottom' },
                    isStacked: true,
                };

                // Instantiate and draw our chart, passing in some options.
                var chart = new google.charts.Bar(document.getElementById('chart_div'));

                chart.draw(data, google.charts.Bar.convertOptions(options));
            }
        </script>
    </head>
<body>
    <div class="container" style="margin:40px;">
        <div class="row">
            <div class="col-md-12" style="text-align: center;">
                <h2>Django Google Bar Chart Example Tutorial - Tuts-Stations.com</h2>
                <div id="chart_div" style="width: 900px; height: 500px;display: inline-block;"></div>
            </div>
        </div>
    </div>
</body>
</html>

Step 7: 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 . import views

urlpatterns = [
    path('', views.googleChart),
]

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 http://localhost:8000/ address with a web browser.

I Hope It will help you....

Happy Coding..