Python  

Django Web framework Google Chart Example

Django is a Python web framework that promotes a quick web development process that follows the MVT (Model View Templates) pattern. Also, having a built-in admin database interface allows easy management of handling data.

MVT (Model-View-Template)

The model explains the complete data structure of the database; here, each table defined as classes, such as data schema, will be included with the business logic of applications.

The view is responsible for handling client page requests and responses with HttpResponse class from django.Http library.

Templates is an Html view page stored in the templates folder. It is configured from the urls.py file. Data's passing form view to Template view by client-side page name.

Structure

myapp/
    __init__.py
    admin.py
    apps.py
    models.py
    views.py
    templates/
        myapp/
            template.html
    static/
        myapp/
            style.css
    migrations/
        __init__.py

URL Configuration

from django.urls import path
from . import views
urlpatterns = [ 
    path('chart/', views.chart, name='chart'),
]

I will have a curve chart example with a simple Google chart library. Templates html code and view.py business logic example are below.

<!DOCTYPE html>
<html>
<head>
    <title>Google Charts Example</title>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
        google.charts.load('current', {'packages':['corechart']});
        google.charts.setOnLoadCallback(drawChart);
        function drawChart() {
            var data = google.visualization.arrayToDataTable({{ data|safe }});
            var options = {
                title: 'Company Performance',
                curveType: 'function',
                legend: { position: 'bottom' }
            };
            var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
            chart.draw(data, options);
        }
    </script>
</head>
<body>
    <div id="curve_chart" style="width: 900px; height: 500px"></div>
</body>
</html>

View.py

def chart(request):
    data = [
        ['Year', 'Sales', 'profit','loss','Expenses'],
        ['2025',3000,2100,1300,300],['2024',3000,1000,1300,300],
         ['2023', 4000,2000,1300,300],['2016',1554,4000,1030,540]
    ]
    context = {
        'data': json.dumps(data)
    }
    return render(request, 'chart.html', context)

Output

Company performance output