Error trying to switch between different charts - python

I am developing an application which shows the data created in a chartjs graph, what I am doing it does well, since all the data is displayed in the way I want, but I have a problem and that is that now I am trying to do that according to the type of graph that a user wants this to be changed, the problem is that the graph is changed but in case of having multiple graphs only the first graph is changed, the others continue with the graph by default, this is my template:
<select name="chartType" id="chartType" onchange="updateChart()" data-role="select">
<option value="pie">pie</option>
<option value="bar">Bar</option>
</select>
<canvas id="{{ project.slug }}" width="400" height="400"></canvas>
This is my script:
var faltante = 100 - {{ project.porcent }};
var data = {
labels: ['{{ project.name }}', 'Falta'],
datasets: [{
data: [{{ project.porcent }}, faltante],
backgroundColor: ['#252850', '#f44611']
}],
};
var ctx = document.getElementById('{{ project.slug }}').getContext('2d');
var myChart = new Chart(ctx, {
type: 'pie',
data: data
});
function updateChart() {
myChart.destroy();
myChart = new Chart(ctx, {
type: document.getElementById("chartType").value,
data: data
});
}

You can invoke your updateChart function with the selected chart type as follows:
onchange="updateChart(this.value)"
Everything could then be done inside the updateChart function.
destroy the chart if it already exists
create the new chart with the specified type
To make this work, you'll also have to explicitly invoke updateChart once with the initial chart type.
updateChart('pie');
Please take a look at below runnable code snippet and see how it works.
let myChart;
function updateChart(type) {
if (myChart) {
myChart.destroy();
}
myChart = new Chart('chart', {
type: type,
data: {
labels: ['A', 'B'],
datasets: [{
data: [3, 6],
backgroundColor: ['#252850', '#f44611']
}]
},
options: {
scales: {
yAxes: [{
display: type == 'bar',
ticks: {
beginAtZero: true
}
}]
}
}
});
}
updateChart('pie');
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<select name="chartType" id="chartType" onchange="updateChart(this.value)" data-role="select">
<option value="pie">Pie</option>
<option value="bar">Bar</option>
</select>
<canvas id="chart" height="100"></canvas>

Related

Django - How to obtain corresponding row values from el-table after performing row-click?

I created a table in Django where upon doing row-click, the records for the corresponding row should be POSTED to the function "medicineRequestSelect" in view_doctor.py. However, it is unable to extract that row of values as shown in Image 1. It returns me None values.
I am relatively new to web development and any help or advice will be greatly appreciated!
<doctor_emr.html>
{% block mainbody%}
{% verbatim %}
<div id="app2" class="container">
<div class="emr-table">
<el-table
ref="multipleTable"
:data="list"
stripe
style="width: 50%"
#row-click="handle"
#selection-change="handleSelectionChange">
<el-table-column
prop="id"
label="Index">
</el-table-column>
<el-table-column
prop="order_id"
label="Order ID">
</el-table-column>
<el-table-column
prop="ward_number"
label="Ward No.">
</el-table-column>
<el-table-column
prop="prop"
label="Scan QR"
width="width">
<template slot-scope="{row$index}">
<el-button #click="onScanQR(row)" type="warning" icon="el-icon-camera" size="mini">Scan</el-button>
</template>
</el-table-column>
</el-table>
</div>
</div>
{% endverbatim %}
<script>
new Vue({
el: '#app2',
data() {
return {
list: []
}
},
mounted() {
this.getemrList()
},
methods: {
getemrList() {
// Obtain EMR list
axios.post(ToDJ('emrList'), new URLSearchParams()).then(res => {
if (res.data.code === 0) {
console.log(res.data.data)
this.list = res.data.data
} else {
this.NotifyFail(res.data.data)
}
})
},
// Purpose: For the row click
handle(row, event, column) {
console.log(row, event, column)
axios.post(ToDJ('medicineRequestSelect'), new URLSearchParams()).then(res => {
if (res.data.code === 0) {
console.log(res.data.data)
this.list = res.data.data
let index = this.list.findIndex(item => {
return item.id == row.id
})
if (index == -1) {
this.$refs.multipleTable.toggleRowSelection(row, true);
this.list.push(row)
} else {
this.$refs.multipleTable.toggleRowSelection(row, false);
this.list.splice(index, 1)
}
} else {
this.NotifyFail(res.data.data)
}
})
},
onScanQR(row) {
this.dialogFormVisible = true;
this.tmForm={...row}
},
// Success notification
NotifySuc(str) {
this.$message({
message: str,
type: 'success'
})
},
// Error notification
NotifyFail(str) {
this.$message({
message: str,
type: 'warning'
})
}
}
})
</script>
{% endblock %}
<view_doctor.py>
#api_view(['GET',"POST"])
def medicineRequestSelect(request):
id = request.POST.get('id')
order_id = request.POST.get('order_id')
ward_number = request.POST.get('ward_number')
print("Values: ", id, order_id, ward_number)
return Action.success()
Image 1: Output Obtained
Image 2: Table I created
I'm also learning, and I try to progress by trying to help other's problem.
First where are you getting your data's from? From your Models?
So if I understood correctly you should import the model you want your data from and then make queries to it using your model.
model = TheNameOfYourModel.objects.all()
and then you can make your queries using q
PS: I'm still learning, i'm curious to see the answer of someone experienced

Highcharts. Django won't load. Highcharts with Django

There is a wonderful library of js - Highcharts. I'm trying to link it to Django, and everything actually works, but not when I'm trying to insert a variable with content into data. Here's the code.
This function returns what I substitute in data in Highcharts.
def get_series(context):
data_ser = []
for i in context:
if i in ['One', "Two", "Three", "Four", "Five"]:
data_ser.append({
'name': i,
'y': context[i],
'z': 22.2
})
data_ser = json.dumps(data_ser)
return data_ser
And this is the jquery code itself:
<script>
$(document).ready(function () {
var data_ser = '{{ data_ser|safe }}'
console.log(data_ser)
Highcharts.chart('container', {
chart: {
type: 'variablepie'
},
title: {
text: 'Stats'
},
series: [{
minPointSize: 10,
innerSize: '20%',
zMin: 0,
name: 'countries',
data: data_ser
}]
});
})
</script>
In series in data, I try to substitute data_ser, but the graph is not output. Although, if you write it manually, then everything will work.
Similar code works:
<script>
$(document).ready(function () {
var data_ser = '{{ data_ser|safe }}'
console.log(data_ser)
Highcharts.chart('container', {
chart: {
type: 'variablepie'
},
title: {
text: 'Stats'
},
series: [{
minPointSize: 10,
innerSize: '20%',
zMin: 0,
name: 'countries',
data: [
{
"name": "One",
"y": 50.0,
"z": 22.2
}]
}]
});
})
</script>
I really hope for help. Or give at least alternative js libraries with graphs where this will work.
It looks like the issue is that data_ser is a string that represents a JavaScript object, but it is being treated as a string in the data property of the series object.
Try it with:
<script>
...
var data_ser = JSON.parse('{{ data_ser|safe }}')
...
</script>

Chart JS only showing first 2 values

I'm using this for my chart application right now
<script>
var canvas = document.getElementById('myChart');
new Chart(document.getElementById("myCanvas"), {
type: 'line',
data: {
labels: mon_unique,
datasets: [{
data: values,
borderColor: "#3e95cd",
fill: false
},
]
},
options: {
title: {
display: true,
},
hover: {
mode: 'index',
intersect: true
},
}
});
</script>
values, what I called my data in my flask app, is a list of numbers. When I change data: [0,1,2,3,4] it graphs it, but it doesn't pass in my values at all.
data = remove_err_str
return render_template('graphing.html', values=data)
This displays only the first two points in values. Values is a list of about 50,000 items. It looks like ['1243.42','2`,...]
<body>
<canvas id="myChart" width="400" height="400"></canvas>
<script>
var canvas = document.getElementById('myChart');
new Chart(document.getElementById("myChart"), {
type: 'line',
data: {
datasets: [{
data: {{values | safe}},
borderColor: "#3e95cd",
fill: false
},
]
},
options: {
title: {
display: true,
test: "Chart for the sweep data"
},
hover: {
mode: 'index',
intersect: true
},
}
});
</script>
</body>
This is the solution I found
Graphing HTML page
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.0.0/Chart.bundle.js"></script>
</head>
<body>
<canvas id="myChart" width="1600" height="800"></canvas>
<script>
var canvas = document.getElementById('myChart');
var chart = new Chart(canvas, {
type: 'line',
data: {
labels: {{ labels | safe }},
datasets: [{
label: "Line chart for sweep data",
data: {{ values | safe }},
fill: false
}]
},
options: {
responsive: false,
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}}}
);
</script>
Every item needs a label. If it gets passed in without a label it won't graph. Also I changed the 'beginAtZero' to be set to true, otherwise it starts the lowest y value in the list. To create labels for every value I did this in my flask app.py
for i in data: #turns it from a list of string values to float values
float_data.append(float(i))
count = count + 1
label_arr.append(count)
return render_template('graphing.html', values=float_data, labels=label_arr)
:*]
You are passing data from python-end to front-end so you have to use jinja template inside your code and for that double-brackets can be used
<script>
var canvas = document.getElementById('myChart');
new Chart(document.getElementById("myCanvas"), {
type: 'line',
data: {
labels: mon_unique,
datasets: [{
data: {{values | tojson}},
borderColor: "#3e95cd",
fill: false
},
]
},
options: {
title: {
display: true,
},
hover: {
mode: 'index',
intersect: true
},
}
});
</script>

change context after the response in sent in django

I have a django view and I'm expecting some of the data in the context to change a few times a second. Can I load a new context into the template after the response is sent without sending a new request? Thanks.
the view
def debug(request):
return render(request, 'all/debug.html', context={"x": x, "y": y})
the template
<div class="container">
<canvas id="data"></canvas>
<div class="graphing">
<select class="graph-select"></select>
<canvas id="graph" width="500"></canvas>
</div>
</div>
<script>
let y = "{{ y }}";
let x = "{{ x }}"
Chart.defaults.global.animation.duration = 0;
var ctx = document.getElementById('graph').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
labels: x.split` `.map(n => +n),
datasets: [{
label: 'My First dataset',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: y.split` `.map(n => +n)
}]
},
// Configuration options go here
options: {
responsive: false,
}
});
</script>
What I want is to dynamically change the x and y data without sending a new request
you should use ajax tech in your template.
here you can find some informations.
just change the view to this
`
-
if somthing happens :
return render(request, 'all/debug.html', context={"z": z, "t": t})
else:
return render(request, 'all/debug.html', context={"x": x, "y": y})
return render(request, 'all/debug.html', context={"x": x, "y": y})
`

Why is Python's json.dumps refusing to serialise strings from my objects?

My objects are not being serialised correctly from my Django site when using Python's json.dumps(). I've got a class which is designed to make the injection of data into Chart.js components:
class ChartData:
def __init__(self):
self.labels = []
self.data = []
self.background_colours = []
self.hover_background_colours = []
def add_datum(self, label, datum, background_colour=None, hover_background_colour=None):
self.labels.append(label)
self.data.append(datum)
self.background_colours.append(background_colour)
self.hover_background_colours.append(hover_background_colour)
def get_converted_data(self):
return json.dumps({'labels': self.labels, 'data': self.data, 'background_colours': self.background_colours,
'hover_background_colours': self.hover_background_colours})
A calling method takes a Quiz as an input, and adds data from its associated Subject items:
def get_subject_chart_data(quiz):
subjects = Subject.objects.filter(question__quizquestion__quiz=quiz).distinct()
chart_data = ChartData()
for subject in subjects:
chart_data.add_datum(subject.name, subject.question_set.filter(quizquestion__quiz=quiz).count())
return chart_data.get_converted_data()
This converted data is then sent injected into the context for the page to be rendered.
def get_context_data(self, **kwargs):
context = super(QuizDetail, self).get_context_data(**kwargs)
quiz = self.get_object()
context['subject_chart_data'] = self.get_subject_chart_data(quiz)
return context
Following this, it's rendered into an {% include %} statement, being passed in as the chart_data argument:
{% include 'snippets/pie_chart.html' with chart_data=subject_chart_data chart_id='subject_chart' chart_height=400 chart_width=400 %}
Finally, the HTML renders the chart using the chart_data passed in:
<canvas id="{{ chart_id }}" width="{{ chart_width }}" height="{{ chart_height }}"></canvas>
<script>
var ctx = document.getElementById("{{ chart_id }}");
var chart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: {{ chart_data.labels|safe }},
datasets: [
{
data: {{ chart_data.data|safe }},
backgroundColor: {{ chart_data.background_colours|safe }}
}]
}
});
</script>
Given how I've seen json.dumps() used in the below example from Python docs, I would expect it to work.
>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'
However, it turns out like this:
var chart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ,
datasets: [
{
data: ,
backgroundColor:
}]
}
});
However, if I pass each attribute of the ChartData to json.dumps(), as such:
def get_converted_data(self):
return {'labels': json.dumps(self.labels), 'data': json.dumps(self.data),
'background_colours': json.dumps(self.background_colours),
'hover_background_colours': json.dumps(self.hover_background_colours)}
It works with no problems:
var chart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ["Geo"],
datasets: [
{
data: [2],
backgroundColor: [null],
hoverBackgroundColor: [null]
}]
}
});
The second version of get converted data works because it is a dict and your template wants chartdata dot data and chart data dot background colours. The template is accessing the dict to get those values, which is why when you use a dict with json encoded values it works. The first version json encodes the whole dict as a string that the django template cannot read into.
You can transform your dict of python variables into a dict of json encoded variables like this:
data = {'labels': self.labels, 'data': self.data, 'background_colours': self.background_colours, 'hover_background_colours': self.hover_background_colours}
data_json = {k:json.dumps(v) for k, v in data.items()}

Categories