Google line chart not printing in Django

Viewed 99

I'm doing a project on covid visualization i.e., when a user selects a particular state, date range, and output type corresponding to the input we get output as a graph for which I'm using Google API to display line charts. The problem occurring now is graph is not displayed on the website but data is passing from backend python views to HTML.

HTML


    <div id="chart_div">
      <script type="text/javascript">

          google.charts.load('current', {packages: ['corechart', 'line']});
          google.charts.setOnLoadCallback(drawBasic);
          function drawBasic() {
              var data = new google.visualization.DataTable();
              data.addColumn('string', 'X');
              data.addColumn('number', {{user_required_type_json|safe}});

              data.addRows({{chart_list_json|safe}});

              var options = {
              hAxis: {
                  title: 'Dates',
                  textStyle: {
                      color: '#1a237e',
                      fontSize: 14,
                      fontName: 'Calibri',
                      bold: true
                  },
                  titleTextStyle: {
                      color:'#1a237e',
                      fontSize: 22,
                      fontName: 'Calibri',
                      bold: true,
                  },
              },
              vAxis: {
                  title: {{user_required_type_json|safe}},
                  textStyle: {
                  color: '#1a237e',
                  fontName: 'Calibri',
                  fontSize: 18,
                  bold: true
                  },
                  titleTextStyle: {
                      color: '#1a237e',
                      fontName: 'Calibri',
                      fontSize: 22,
                      bold: true
                  },
              },
              title: {{user_input_state_json|safe}}+' '+{{user_required_type_json|safe}}+' Data'
              };

              var chart = new google.visualization.LineChart(document.getElementById('chart_div'));

              chart.draw(data, options);
              }

      </script>
  </div>

views.py

import json
from django.shortcuts import render
from django.http import HttpResponse
import requests
import datetime as dt


def indexview(request):
    url=requests.get('https://data.covid19india.org/v4/min/timeseries.min.json')
    json_data=url.json()

    user_input_state=''
    user_input_date_from='2021-10-01'
    user_input_date_to='2021-10-10'
    user_data_type=''
    user_required_type=''
    if request.method == 'POST': 
        user_input_state=request.POST.get('state') 
        user_input_date_from=request.POST['date_from']
        user_input_date_to=request.POST['date_to']
        user_data_type=request.POST.get('data_period') #cumulative or daily
        user_required_type=request.POST.get('required_type') #confirmed, recovered.....
        #To store dates list

    # print('State is '+user_input_state)
    # print('Date from '+user_input_date_from)
    # print('User date is '+user_input_date_to)
    # print('User data type '+user_data_type)
    # print('User required type is '+user_required_type)
    start_date =user_input_date_from
    end_date = user_input_date_to
    start_date_object = dt.datetime.strptime(start_date,"%Y-%m-%d").date()
    end_date_object = dt.datetime.strptime(end_date,"%Y-%m-%d").date()
    days = end_date_object - start_date_object
    dates=[]
    otp=[]
    for i in range(days.days+1):
        dates.append(str(start_date_object+dt.timedelta(days=i)))
    
    for i in dates:
        try:
            otp.append(json_data[user_input_state]['dates'][i][user_data_type][user_required_type])
        except KeyError:
            otp.append(0)

    chart_list = [list(a) for a in zip(dates,otp)]
    #chart_list.insert(0,['Dates','Values'])
    chart_list_json=json.dumps(chart_list)
    user_input_state_json=json.dumps(user_input_state)
    user_required_type_json=json.dumps(user_required_type)
    dict_pass={
        'dates':dates,
        'otp':otp,
        'chart_list':chart_list,
        'chart_list_json':chart_list_json,
        'user_input_state_json':user_input_state_json,
        'user_required_type_json':user_required_type_json
        }
    return render(request,'index.html',dict_pass)
    

Website displaying like this enter image description here

Can anyone please explain why my graph is not displaying tomorrow is my submission date.
Thanks in advance

1 Answers

just noticed the <script> element is inside the chart's <div> element.
when the google chart is drawn, it is going to replace any contents within the <div>
recommend moving the <script> outside of the <div>

otherwise, the chart seems to work fine with the data provided.

see following working snippet...

google.charts.load('current', {
  packages: ['corechart', 'line']
});
google.charts.setOnLoadCallback(drawBasic);

function drawBasic() {
  var data = new google.visualization.DataTable();
  data.addColumn('string', 'X');
  data.addColumn('number', 'test');

  data.addRows([["2021-10-01", 809], ["2021-10-02", 865], ["2021-10-03", 765], ["2021-10-04", 429], ["2021-10-05", 671], ["2021-10-06", 800], ["2021-10-07", 643], ["2021-10-08", 693], ["2021-10-09", 629], ["2021-10-10", 624], ["2021-10-11", 310], ["2021-10-12", 503], ["2021-10-13", 517], ["2021-10-14", 540], ["2021-10-15", 586]]);

  var options = {
    hAxis: {
      title: 'Dates',
      textStyle: {
        color: '#1a237e',
        fontSize: 14,
        fontName: 'Calibri',
        bold: true
      },
      titleTextStyle: {
        color: '#1a237e',
        fontSize: 22,
        fontName: 'Calibri',
        bold: true,
      },
    },
    vAxis: {
      title: 'test',
      textStyle: {
        color: '#1a237e',
        fontName: 'Calibri',
        fontSize: 18,
        bold: true
      },
      titleTextStyle: {
        color: '#1a237e',
        fontName: 'Calibri',
        fontSize: 22,
        bold: true
      },
    },
  };

  var chart = new google.visualization.LineChart(document.getElementById('chart_div'));

  chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Related