I'm trying to display pie and bar chart using Flask API on html page using chart.js. I am able to display pie chart but bar chart is getting below error.
"cannot read property of undefined (reading 'offsetWidth')" under "/nutrition_analysis" route.
Please find below Python main.py code,
# importing the necessary dependencies
from flask import Flask, render_template, request,jsonify
from flask_cors import CORS, cross_origin
import pandas as pd
from flask import send_file
#import matplotlib.pyplot as plt
#%matplotlib inline
import logging
from datetime import datetime
app = Flask(__name__) # initializing a flask app
#app.route('/', methods=['GET', 'POST']) # route to display the home page
#cross_origin()
def homePage():
return render_template("home.html")
#app.route('/form_fill',methods=['GET','POST']) # route to display the home page
#cross_origin()
def form_fill():
return render_template("form_fill.html")
#app.route('/download_file',methods=['GET','POST']) # route to display the home page
#cross_origin()
def download_file():
path = 'Daily Nutrition Requirement.xlsx'
return send_file(path, as_attachment=True)
#app.route('/nutrition_analysis',methods=['POST','GET']) # route to show the predictions in a web UI
#cross_origin()
def nutrition_analysis():
if request.method == 'POST':
try:
# reading the inputs given by the user
name = (request.form['name'])
age = float(request.form['age'])
weight = float(request.form['weight'])
reference = (request.form['reference'])
phone = float(request.form['phone'])
emailid = (request.form['emailid'])
file = request.form['customer_data']
customer_data = pd.read_excel(file)
RDA = pd.read_excel('Recommended_Nutrition.xlsx')
df = pd.concat([RDA, customer_data], ignore_index=True)
df_Carbs = df[df["Nutrients"] == "Carbohydrate"]
df_Fat = df[df["Nutrients"] == "Fats"]
df_Prot = df[df["Nutrients"] == "Proteins"]
df_Fbr = df[df["Nutrients"] == "Fiber"]
df_Macros = pd.concat([df_Carbs, df_Fat, df_Prot, df_Fbr])
df_Macros_Exp = df_Macros[df_Macros["Category"] == "Exp"]
# df_Macros_Obs = df_Macros[df_Macros["Category"] == "Obs"]
# plt.pie(df_Macros_Exp["Value"], labels=df_Macros_Exp["Nutrients"], autopct='%1.1f%%')
# plt.title("Expected Macros as per RDA", fontweight='bold')
# plt.savefig('chart.png')
values = df_Macros_Exp["Value"].tolist()
labels = df_Macros_Exp["Nutrients"].tolist()
colors = ["#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA"]
# Bar Chart
df_stack = pd.merge(RDA,customer_data[['Nutrients','Value']],on='Nutrients', how='left')
df_stack1=df_stack[['Nutrients','Value_x','Value_y']].copy()
df_stack1["RDA"]=100
df_stack1["Intake"]=((df_stack1["Value_y"] - df_stack1["Value_x"])/df_stack1["Value_x"])*100
df_stack1.drop(["Value_x", "Value_y"], axis = 1, inplace = True)
def color(x):
if x < 0 or x > 50 :
return '#F7464A'
else:
return '#46BFBD'
df_stack1["Color"]=df_stack1["Intake"].apply(color)
values_bar = df_stack1["Intake"].tolist()
labels_bar = df_stack1["Nutrients"].tolist()
colors_bar = df_stack1["Color"].tolist()
#dt=datetime.now()
# showing the prediction results in a UI
return render_template('nutrition_analysis.html',s1=name,s2=age,s3=weight,s4=reference,s5=phone,s6=emailid,set=zip(values, labels, colors),set2=zip(values_bar,labels_bar,colors_bar))
except Exception as e:
print('The Exception message is: ',e)
logging.debug(e)
return 'something is wrong'
# return render_template('results.html')
else:
return render_template('home.html')
if __name__ == "__main__":
logging.basicConfig(filename='Nutrition_Analysis.log', level=logging.DEBUG)
app.run(host='127.0.0.1', port=8001, debug=True)
#app.run(debug=True) # running the app
Please find html page which need to be rendered below,
<head>
<meta charset="utf-8" />
<title>Macro Analysis</title>
<script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js'></script>
</head>
<body>
<div class="item active" style="display: flex; height: 100px;">
<div style=" width: 30%;">
<h1><p>Liv365 Nutrition Analysis Report :</p></h1>
<br>name : {{s1}}</br>
<br>age : {{s2}}</br>
<br>weight : {{s3}}</br>
<br>reference : {{s4}}</br>
<br>phone : {{s5}}</br>
<br>emailid : {{s6}}</br>
</div>
<div style=" width: 30%;">
<h1>Macro Analysis</h1>
<canvas id="chart" width="400" height="200"></canvas>
<script>
var pieData = [
{% for values, labels, colors in set %}
{
value: {{values}},
label: "{{labels}}",
color : "{{colors}}"
},
{% endfor %}
];
// draw pie chart
new Chart(document.getElementById("chart").getContext("2d")).Pie(pieData);
</script>
</div>
<div style=" width: 40%;">
<h1>Micro Analysis</h1>
<canvas id="bar" width="400" height="200"></canvas>
<script>
var barData = [
{% for values_bar, labels_bar, colors_bar in set2 %}
{
value: {{values_bar}},
label: "{{labels_bar}}",
color : "{{colors_bar}}"
},
{% endfor %}
];
new Chart(document.getElementById("bar"), {
type: 'bar',
data: {
labels: barData["label"],
datasets: [
{
label: "Population (millions)",
backgroundColor: barData["color"],
data: barData["value"]
}
]
},
options: {
legend: { display: false },
title: {
display: true,
text: 'Total Confirmed Cases of COVID in May'
}
}
});
</script>
</div>
</div>
</body>
</html>
Please help me resolve this issue.
Thanks in advance!!!
Regards,
Rohan
Related
I want to display countries and states in Django form, for that I am trying to get data from json, create form, pass json data to form and get state of the country on ajax request. I managed to write the process as far as I learned, but at last form is not rendered on Django template. How can I render Django form with following code structure?
My Model:
from django.db import models
class Address(models.Model):
country = models.CharField(null=True, blank=True, max_length=100)
state = models.CharField(null=True, blank=True, max_length=100)
def __str__(self):
return '{} {}'.format(self.country, self.state)
My Forms.py:
import json
def readJson(filename):
with open(filename, mode="r", encoding="utf-8") as fp:
return json.load(fp)
def get_country():
""" GET COUNTRY SELECTION """
filepath = './static/data/countries_states_cities.json'
all_data = readJson(filepath)
all_countries = [('-----', '---Select a Country---')]
for x in all_data:
y = (x['name'], x['name'])
all_countries.append(y)
return all_countries
def return_state_by_country(country):
""" GET STATE SELECTION BY COUNTRY INPUT """
filepath = './static/data/countries_states_cities.json'
all_data = readJson(filepath)
all_states = []
for x in all_data:
if x['name'] == country:
if 'states' in x:
for state in x['states']:
y = (state['name'], state['name'])
all_states.append(state['name'])
else:
all_states.append(country)
return all_states
class AddressForm(forms.ModelForm):
country = forms.ChoiceField(
choices = get_country(),
required = False,
label='Country / Region*',
widget=forms.Select(attrs={'class': 'form-control', 'id': 'id_country'}),
)
class Meta:
model = Address
fields = ['country']
My Form.html
<form class="" action="" method="post">
{% csrf_token %}
{% for error in errors %}
<div class="alert alert-danger mb-4" role="alert">
<strong>{{ error }}</strong>
</div>
{% endfor %}
<div class="row">
<div class="col-lg-6">
<div class="mb-4">
{{ form.country}}
</div>
</div>
<div class="col-lg-6">
<div class="mb-4">
<div class="form-group">
<label >Select a Province/State</label>
<select id="id_province" class="form-control" name="state">
<option value="-----">Select Province/State</option>
</select>
</div>
</div>
</div>
</div>
</form>
My Views:
def readJson(filename):
with open(filename, mode="r", encoding="utf-8") as fp:
return json.load(fp)
def return_state_by_country(country):
""" GET STATE SELECTION BY COUNTRY INPUT """
filepath = './static/data/countries_states_cities.json'
all_data = readJson(filepath)
all_states = []
for x in all_data:
if x['name'] == country:
if 'states' in x:
for state in x['states']:
y = (state['name'], state['name'])
all_states.append(state['name'])
else:
all_states.append(country)
return all_states
def getProvince(request):
country = request.POST.get('country')
provinces = return_state_by_country(country)
return JsonResponse({'provinces': provinces})
def processForm(request):
context = {}
if request.method == 'GET':
form = AddressForm()
context['form'] = form
return render(request, './ecommerce/checkout.html', context)
if request.method == 'POST':
form = AddressForm(request.POST)
if form.is_valid():
selected_province = request.POST['state']
obj = form.save(commit=False)
obj.state = selected_province
obj.save()
return render(request, './ecommerce/checkout.html', context)
My Ajax:
<script>
$("#id_country").change(function () {
var countryId = $(this).val();
$.ajax({
type: "POST",
url: "{% url 'ecommerce:get-province' %}",
data: {
'csrfmiddlewaretoken': '{{ csrf_token }}',
'country': country
},
success: function (data) {
console.log(data.provinces);
let html_data = '<option value="-----">Select Province/State</option>';
data.provinces.forEach(function (data) {
html_data += `<option value="${data}">${data}</option>`
});
$("#id_province").html(html_data);
}
});
});
</script>
I am trying to print form.country on template but its not working. What could be the problem?
With ModelForms I find that this type of configuration, in which everything falls under class Meta: works.
However im dubious about that get_country() method. If you share it I can take a deeper look and maybe even test it to make sure that it's not doing anything funky.
If your list of countries is somewhat static and not too long you might wanna consider using a TextChoices enum type in your model attribute to limit the choice selection. Django forms will automatically render a dropdown widget listing the items from your enum.
You can checkout this answer if you want to look into that, which further links to the django docs.
class AddressForm(forms.ModelForm):
class Meta:
model = Address
fields = ['country']
widgets = {
"country": forms.ChoiceField(
choices = get_country(),
attrs={
"class": "form-control",
"id": "id_country"
}
),
}
labels = {
"country" : "Company Country Location"
}
I have a problem displaying data into a mixed bar and line chart from an API designed using the Django Rest Framework. Here is the model for the readings from the pressure and flowrate sensors
models.py
from django.db import models
# Create your models here.
class ReadingQuerySet(models.QuerySet):
pass
class ReadingManager(models.Manager):
def get_queryset(self):
return ReadingQuerySet(self.model, using=self._db)
class Reading(models.Model):
date = models.DateField(auto_now=True)
pressure =models.IntegerField(default=0)
flowrate =models.IntegerField(default=0)
timestamp =models.TimeField(auto_now_add=True)
objects = ReadingManager()
def __str__(self):
return str(self.timestamp) + ' ' + 'Pressure: ' + str(self.pressure) + ' ' + 'Flowrate: ' + str(self.flowrate)
The code for the serializer is here.
serializers.py
from rest_framework import serializers
from app.models import Reading
class ReadingSerializer(serializers.ModelSerializer):
class Meta:
model = Reading
fields = ['id','date','timestamp','pressure','flowrate']
the serializer is in an api folder i placed within a django app. the code for the APIview is below.
views.py
from rest_framework import generics, mixins
from rest_framework.response import Response
from .serializers import ReadingSerializer
from app.models import Reading
class ReadingChartAPIView(mixins.CreateModelMixin, generics.ListAPIView):
permission_classes = []
authentication_classes = []
serializer_class = ReadingSerializer
def get(self, request, *args, **kwargs):
qs = Reading.objects.all()
data = {
'timestamp':qs.values('timestamp'),
'pressure':qs.values('pressure'),
'flowrate':qs.values('flowrate'),
'update':qs.values('pressure', 'flowrate').last()
}
return Response(data)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
and this is the data i receive from the APIview
{"timestamp":[{"timestamp":"12:44:11.487901"},{"timestamp":"14:12:58.410520"},{"timestamp":"01:56:56.485449"},{"timestamp":"01:57:14.184429"},{"timestamp":"01:57:34.366559"},{"timestamp":"13:12:43.469454"}],"pressure":[{"pressure":45},{"pressure":35},{"pressure":79},{"pressure":52},{"pressure":89},{"pressure":27}],"flowrate":[{"flowrate":56},{"flowrate":67},{"flowrate":83},{"flowrate":14},{"flowrate":74},{"flowrate":46}],"update":{"pressure":27,"flowrate":46}}
The issue is in my html file when i am extracting this data. Here is my HTML.I am stuck and open to any solutions. i am trying to push the data labels for to datasets every after 5 seconds starting from the first one.
{% extends "layouts/base.html" %}
{%load static %}
{% block title %} Dashboard {% endblock %}
<!-- Specific Page CSS goes HERE -->
{% block stylesheets %}{% endblock stylesheets %}
{% block content %}
{% block jquery %}
<script type="text/javascript">
var counter = 0
var limit = 6
var chart = $('#myChart')
var endpoint = '/api/chart'
var pressures = []
var flowrates = []
var timestamps = []
var pressure_new = []
var flowrate_new = []
$.ajax({
method: 'GET',
url: endpoint,
success: function(data){
console.log(data)
}
})
var getData =
$.ajax({
method: 'GET',
url: endpoint,
success: function(data){
timestamps = data.timestamp.map(b => b.timestamp);
pressures = data.pressure.map(a => a.pressure);
flowrates = data.flowrate.map(c => c.flowrate);
myChart.data.labels.concat(timestamps[counter]);
myChart.data.datasets[0].data.concat(pressures[counter]);
myChart.data.datasets[1].data.concat(flowrates[counter]);
counter++;
myChart.update();
}
});
setInterval(getData, 3000)
</script>
{% endblock %}
<div class="container-fluid">
<div class="page-header row no-gutters py-4">
<div class="col-12 col-sm-4 text-center text-sm-left mb-0">
<span class="text-uppercase page-subtitle">Dashboard</span>
<h3 class="page-title">Overview</h3>
</div>
</div>
<div class="row">
<div class="col-lg-8 col-md-12 col-sm-12 mb-4">
<div class="card" width = '18rem' height = '10rem'>
<div class="card-header border-bottom">
<h5 class="card-title">Pressure and Flowrate</h5>
<h6 class="card-subtitle mb-1 text-muted">Real-time Readings of Pressure and Flowrate</h6>
</div>
<div class="card-body">
<canvas id="myChart"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js"></script>
<script>
function setChart(){
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'Pa',
data:[],
backgroundColor:'rgba(255, 99, 132, 0.2)',
borderColor:'rgba(255, 99, 132, 1)',
borderWidth: 1
}, {
label: 'cm3/min',
data:[],
backgroundColor:'rgba(54, 162, 235, 0.2)',
borderColor:'rgba(54, 162, 235, 1)',
type: 'line',
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
};
setChart()
</script>
</div>
</div>
</div>
I am trying to access my database called Active_Project_View. Inside of this is the information I am trying to display in ag-grid. I have used the objects.all() to get the information out but it's not work.
class getActiveGrid():
def get_queryset(self, request, format=None):
queryset = Active_Project_View.objects.all()
return queryset
def get(self, request, format=None):
filters = request.data
serializer = ActiveGridViewSerializer(self.get_queryset(filters), many=True)
return HttpResponse(serializer.data)
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" href="static\app\content\agGrid.css" >
<script src="https://unpkg.com/ag-grid-community/dist/ag-grid-
community.min.noStyle.js"></script>
<link rel="stylesheet" href="https://unpkg.com/ag-grid-
community/dist/styles/ag-grid.css">
<link rel="stylesheet" href="https://unpkg.com/ag-grid-
community/dist/styles/ag-theme-balham.css">
</head>
<body>
<h1>Project Grids</h1>
<div class="box c">
Active Projects
<script type="text/javascript" charset="utf-8">
const Active_Project = [
{ headerName: "Last Name", field: "app.Customer_Last_Name", sort: 'asc' },
{ headerName: "First Name", field: "Customer_First_Name", },
{ headerName: "Phone Number", field: "Customer_Phone_Number", },
{ headerName: 'Employee', field: 'Employee_First_Name' },
{ headerName: 'Zip Code', field: 'Customer_Zip' },
];
const ActiveProjectGrid = {
columnDefs: Active_Project,
};
var eGridDiv1 = document.querySelector('#ActiveProjectGrid');
new agGrid.Grid(eGridDiv1, ActiveProjectGrid);
fetch('getActiveGrid').then(function (response) {
return response.data();
}).then(function (data) {
ActiveProjectGrid.api.setRowData(data);
})
</script>
</body>
</html>
url(r'^getActiveGrid$',app.views.getActiveGrid, name='postActive'),
class ActiveGridViewSerializer():
class Meta:
model = Active_Project_View
fields= '__all__'
class Active_Project_View(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
Customer_First_Name= models.CharField(max_length=255, blank = False)
Customer_Last_Name = models.CharField(max_length=255, blank = False)
Customer_Phone_Number = models.CharField(max_length=10, blank=True)
Customer_Zip = models.CharField(max_length = 5, blank = False)
Employee_First_Name=models.CharField(max_length=255)
Quote_Status = models.CharField(max_length = 16, default = None)
class Meta:
managed = False
I expect to get the customer name, phone number, zip code and employee to be displayed is the grid. I am currently getting the "loading..." box and I am not sure what I am doing wrong.
There are multiple problems with your implementation. You can fix them one by one like this:
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import serializers
#serializer
class ActiveGridViewSerializer(serializers.ModelSerializer):
class Meta:
model = Active_Project_View
fields= '__all__'
# view
class getActiveGrid(APIView):
def get_queryset(self):
queryset = Active_Project_View.objects.all()
return queryset
def get(self, request, format=None):
serializer = ActiveGridViewSerializer(self.get_queryset(), many=True)
return Response(serializer.data)
# url
url(r'^getActiveGrid$',app.views.getActiveGrid.as_view(), name='postActive'),
i'm working in Django, to draw some graph in function of my modules. ie: if i have 2 modules, i want 2 charts , if 8 modules, 8 charts.
Modules are integreted in a plugin. so i can list all modules found in a plugin. i did this in Django:
def plugin_graph(request, hub_uid, plugin_uid):
request.session['is_admin'] = True
hub = Hub.objects.get(mac=hub_uid)
fields = []
if request.method == 'GET':
if 'field' in request.GET:
fields.append(request.GET['field'])
plugin = Plugin.objects.get(uid=plugin_uid, hub=Hub.objects.get(mac=hub_uid))
#on recupere lensemble desmodules de ce plug
modules = plugin.get_modules_list()
#pour chak module, tracer son graph
for m in modules:
modules_list = {'uid':m.uid,
'name':m.name,
'version':m.version,
'type':m.type,
'time':m.last_time(),
'rssi':m.rssi(),
'status_icon':m.status_icon()}
module = Module.objects.get(uid=m.uid, plugin=Plugin.objects.get(uid=plugin_uid, hub=Hub.objects.get(mac=hub_uid)))
historic = sorted(ModuleDocument.objects.filter(module=module), key=getKey)
values = get_graph_values(historic=historic, dates=None, fields=fields)
print values
field = None if len(fields) < 1 else fields[0]
return render(request, "admin/graph2.html",
{
'values': values,
'hub': hub_uid,
'plugin': plugin_uid,
'uid': m.uid,
'module': module,
'fields': module.get_number_fields(),
'field': field,
'level': 'module',
}
)
After recovering all my modules i draw the charts like that in javascript:
<script>
var ctx = document.querySelector("#chart");
var data = JSON.parse('{{ values }}'.replace(/"/g, '"'));
var labels = [];
var values = [];
var beginAtZero = true;
for (obj in data) {
labels.push(data[obj].x);
values.push(data[obj].y);
if (data[obj].y < 0) {
beginAtZero = false;
}
}
var lineChart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [{
label: "{{field}}",
data: values,
borderColor: '#97168F'
}]
},
options: {
scales: {
xAxes: [{
time: {
unit: 'day'
}
}],
yAxes: [{
ticks: {
beginAtZero:beginAtZero
}
}]
}
}
});
</script>
My problem is just one chart is printed. i would like to put it in a for loop to recuperate all data & labels of each module to draw normally all charts i want.
Thank u for your help
You need to utilise the forloop.counter method in the django template to dynamically name a number of items, otherwise the charts will just get overwritten each time and you are just left with the last chart. Its worth noting that I include this code in the block content not a specific js block.
In the example below, the items that are dynamically named are;
The container div
<div id = 'emg-{{forloop.counter}}'>
The canvas
<canvas id="myChart-{{forloop.counter}}">
The chart JS function name
var func_name = "container-{{forloop.counter}}";
func_name = new Chart(
document.getElementById('myChart-{{forloop.counter}}'),{
type: 'scatter',
I've included the full code below. I appreciate my example is different from your posted code, but it demonstrates the concept of dynamically creating certain elements.
{% for time, name_list, value_list, latitude_list, longitude_list, polyline_list in data %}
{% with forloop.counter as track_object_counter %}
<div id = 'emg-{{forloop.counter}}'>
{% for item in emg_data %}
{% if item.loop_id == track_object_counter %}
<div id = "emg-plot" style="height:15rem; padding-top: 1rem;">
<canvas id="myChart-{{forloop.counter}}">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
var y_data = {{item.data|strip_apostrophe}}
var x_data = '{{item.name}}'
var func_name = "container-{{forloop.counter}}";
func_name = new Chart(
document.getElementById('myChart-{{forloop.counter}}'),{
type: 'scatter',
data: {
datasets: [{
showLine: true,
label: x_data,
data: y_data,
backgroundColor: 'rgba(141,49,123,0.7)',
borderWidth: 2,
borderColor: 'rgba(141,49,123,0.7)'
}],
},
});
</script>
</canvas>
</div>
{% endif %}
{% endfor %}
</div>
{% endwith %}
{% endfor %}
I have implemented chart JS 2.5 into my django application version 1.11 but I am able to see only the canvas but not any bar chart, besides,the web browser console does not display any error, so this is becoming quite difficult for me to trace the mistake.
statistics.html and views.py are my main files where I am currently trying to debug this problem. The urls.py and header.html files were not touched recently and I put them at the end.
statistics.html file:
Graph implementation and retrieval of the JSON object
{% extends "personal_website/header.html"%}
<script>
{% block jquery %}
var endpoint = '/statistics/data'
var defaultData = []
var labels = []
$.ajax({
method: "GET",
url: endpoint,
dataType: 'json',
success: function(data){
labels = data.labels
defaultData = data.default
var ctx = document.getElementById("myChart")
var myChart = new Chart(ctx, {
type:'bar',
data: {
labels: labels,
datasets : [{
label: '# of votes',
data: defaultData,
}]
}
})
},
error: function(error_data){
console.log("error on data")
console.log(error_data)
}
})
{% endblock %}
</script>
{% block content %}
<div class ='row'>
<div class="col-sm-12" url-endpoint='{% url "get_data" %}'>
<h1>Statistics for week 21</h1>
<canvas id="myChart" width="400" height="400"></canvas>
</div>
</div>
{% endblock content %}
Views.py
get_data() was used to test if I could receive the JSON object through the web browser console.
from django.shortcuts import render
from django.views.generic import View
from django.http import JsonResponse
from django.template.loader import render_to_string
from rest_framework.views import APIView
from rest_framework.response import Response
def index(request):
return render(request, 'personal_website/home.html')
def statistics(request):
return render(request, 'personal_website/statistics.html',{})
def get_data(request, *args, **kwargs):
response_data = {}
response_data["customers"] = 100
response_data["sales"] = 40 *12
return JsonResponse(response_data)
class ChartData(APIView):
def get(self,request,format=None):
labels = ["Red","Blue","Yellow","Green","Purple","Orange"]
default_items = [22,35,12,8,10,9]
data = {
"labels": labels,
"default": default_items,
}
return Response(data)
urls.py
from django.conf.urls import url, include
from . import views
from .views import ChartData, get_data
urlpatterns = [
url(r'^$', views.index, name='index'), # home
url(r'^statistics/$', views.statistics, name='statistics'),
url(r'^statistics/data$', get_data, name='get_data'),
url(r'^statistics/chart-data$', ChartData.as_view()), # API View working) ]
header.html
<head>
<title>Statistics</title>
<meta charset="utf-8" />
{% load staticfiles %}
<meta name="viewport" content="width=device=width, initial-scale=1.0">
</head>
<body class="body" style="background-color:#f6f6f6">
<div class="container-fluid" style="min-height:95%; ">
<div class="row">
<div class="col-sm-10">
<h3>Statistics</h3>
</div>
</div><hr>
<div class="well bs-sidebar" id="sidebar">
<ul class="nav nav-pills nav-stacked">
<li><a href='/'>Home</a></li>
<li><a href='/statistics/'>Statistics</a></li>
</ul>
</div>
</div>
<footer>
<!-- no content for the moment-->
</footer>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js">
</script>
</html>
Lastly, the only part that I see that changes is is the label: '# of votes' from the dataset.
What is missing in the code, so I can see the displayed bar charts?
Any help, suggestion, improvement, question is welcome.