How to access objects in my template from Django view? - javascript

I need to display attributes of each object exisiting in data.How can I access the objects in my template?
Views.py
data = []
for e in rep:
data.append({
'time' : e.time,
'power' : e.power
})
return JsonResponse({'data':data},status=200)
template
success : function(response){
console.log(response)
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: [***here i need to access my objects***],
datasets: [{
label: "Consumption",
data: [{% for e in data %}'{{ e.power }}',{% endfor %}]}})
}
Kind regards.

Related

If the entries in the model are made on the same date then the fields of this model must be summed up

I have a model
class paidparking(models.Model):
adress = models.ForeignKey(Parking, on_delete=models.SET_NULL, null=True, verbose_name='Адрес парковки')
carnumber = models.CharField(max_length=150,verbose_name='Номер автомобиля')
amountoftime = models.IntegerField(verbose_name='Количество времени')
price = models.FloatField(verbose_name='Цена')
telephone = models.CharField(max_length=20,verbose_name='Номер телефона')
email = models.EmailField(verbose_name='Электронный адрес',null=True,blank=True )
datetimepaidparking = models.DateTimeField(auto_now_add=True, verbose_name='Дата и время оплаты')
expirationdate = models.DateField(null=True,verbose_name='Дата начала срока действия')
expirationtime = models.TimeField(null=True,verbose_name='Время начала срока действия')
enddateandtime = models.DateTimeField(null=True,blank=True,verbose_name='Окончание срока действия')
There is a function
startdate = datetime.strptime(request.POST['startdate'], '%d.%m.%Y')
enddate = datetime.strptime(request.POST['enddate'], '%d.%m.%Y')
paymentparking = paidparking.objects.filter(expirationdate__range=(startdate, enddate)).values('expirationdate',
'price')
In JS, I get this data and draw graphs
$.ajax({
type: "POST",
url: "date",
data: {
'startdate': finalDateStrStart, 'enddate': finalDateStrEnd,
},
dataType: "json",
cache: false,
success: function (data) {
if (data.result) {
var expirationdates = [];
var prices = [];
for (let i = 0; i < data.result.length; i++) {
expirationdates.push(data.result[i].expirationdate);
prices.push(data.result[i].price);
}
if(window.chart instanceof Chart)
{
window.chart.destroy();
}
var ctx = document.getElementById("line").getContext("2d");
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: expirationdates,
datasets: [{
label: 'Оплата парковочных пространств',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(144,204,244)',
data: prices,
}]
},
options: {
}
});
var ctx = document.getElementById("bar").getContext("2d");
var chart = new Chart(ctx, {
type: 'bar',
data: {
labels: expirationdates,
datasets: [{
label: 'Оплата парковочных пространств',
backgroundColor: 'rgb(144,204,244)',
borderColor: 'rgb(255, 99, 132)',
data: prices,
}]
},
options: {
}
});
}
}
});
return JsonResponse({'result': list(paymentparking)})
As a result, I get:
I need to make a query that would sum the values from the price field for the same date in the expirationdate field
Right now my query outputs all records if the expirationdate field falls within the date range between startdate and enddate
You have to use the trick with values and annotate as described very well here:
from django.db.models import Sum
qs = paidparking.objects.values('expirationdate').annotate(Sum('price'))
# if you want to order by date:
qs = qs.order_by('expirationdate')
This will output a queryset a list of dictionnaries containing expirationdate and price__sum as keys.
Edit:
For your question in the comment, just add the filter at the beginning of the query:
paidparking.objects.filter(expirationdate__range=(startdate, enddate)).values('expirationdate').annotate(Sum('price'))
You need to use annotate in django orm to get the output for the same.
from django.db.models import Sum
PaidParking.objects.values('expirationdate', 'price') \
.annotate(parking_price=Sum('price')) \
.order_by('-expirationdate')
I suppose this answer is suffice for the asked query.
Reference: For Basic understanding of the query how it works follow this link

How to get two output JSON Objects in js line chart?

I would like to display two lines in a Chart.js line chart. The required data from the database I have a JSON file with 2 objects.
Now I want to display them in the line chart. If I only want to display one data set it is no problem. When displaying two lines at the same time I have no idea what to do. I tried to call the objects and then output them, but the output is always undefined.
What am I doing wrong here?
Error:
Cannot read property 'current_week' of undefined
JSON Output:
{"current":[{"current_week":23},{"current_week":636},{"current_week":237}],"last":[{"last_week":235},{"last_week":74},{"last_week":737},{"last_week":767},{"last_week":546},{"last_week":73},{"last_week":453}]}
JS Chart.js Code:
$(document).ready(function() {
$.ajax({
url : "http://localhost/r6team-new/admin/includes/stats/website-weekly-stats.php",
type : "GET",
success : function(data) {
console.log(data);
var current_week = [];
var last_week = [];
for(var i in data) {
current_week.push(data.current[i].current_week);
last_week.push(data.last[i].last_week);
}
console.log(current_week);
console.log(last_week);
var visitorsChart = {
labels: ['MO', 'DI', 'MI', 'DO', 'FR', 'SA', 'SO'],
datasets: [{
type : 'line',
data : current_week,
backgroundColor : 'transparent',
borderColor : '#007bff',
pointBorderColor : '#007bff',
pointBackgroundColor: '#007bff',
fill : false
},
{
type : 'line',
data : last_week,
backgroundColor : 'tansparent',
borderColor : '#ced4da',
pointBorderColor : '#ced4da',
pointBackgroundColor: '#ced4da',
fill : false
}]
};
var ctx = $("#visitors-chart");
var LineGraph = new Chart(ctx, {
data: visitorsChart,
});
},
});
});
your loop is incorrect
var current_week = [];
var last_week = [];
for(var i in data["current_week"]) {
current_week.push(i["current_week"]);
}
for(var i in data["last_week"]) {
last_week.push(i["last_week"]);
}
or make it more easier
$(document).ready(function() {
$.ajax({
url : "http://localhost/r6team-new/admin/includes/stats/website-weekly-stats.php",
type : "GET",
success : function(data) {
var visitorsChart = {
labels: ['MO', 'DI', 'MI', 'DO', 'FR', 'SA', 'SO'],
datasets: [{
...
//current_week
data: data["current"].map(d => d["current_week"])
},
{
...
//last_week
data: data["last"].map(d => d["last_week"])
}]
};
var ctx = $("#visitors-chart");
var LineGraph = new Chart(ctx, {
data: visitorsChart
});
},
});
});

How can I access data provided to HTML template from Python flask routing in my JavaScript code?

So I have a python flask application that routes to a site and passes along two lists:
def chart():
labels = ['x', 'y', 'z']
values = [100, 150, 100]
return render_template('chart.html',
labels=labels, values=values)
I use Chart.min.js and I can then use the lists in rendering a graph in my chart.html:
{% block body %}
<h1>Test chart</h1>
<canvas id="myChart" width="800" height="400"></canvas>
<p id="caption">chart displaying labels n' values</p>
<script type=text/javascript>
var ctx = document.getElementById('myChart');
var names = [
{% for item in labels %}
"{{ item }}",
{% endfor %}
];
var numbers = [
{% for item in values %}
{{ item }},
{% endfor %}
];
var chartData = {
labels: names,
datasets: [{
label: 'values',
data: numbers
}]
};
var myChart = new Chart(ctx, {
type: 'line',
data: chartData
});
</script>
{% endblock %}
Now this works fine and I get a nice pretty graph.
Then I wanted to put my JavaScript in a seperate file in the static folder for my flask application but I cannot find how I'm supposed to access the lists passed along to chart.htlm. I can render a graph just fine if I hardcode some data into the JS file but I can't seem to get the data provided by the python code..
var ctx = document.getElementById('myChart');
// var names = ['x', 'y', 'z'];
// var numbers = [100, 150, 100];
var chartData = {
labels: names,
datasets: [{
label: 'values',
data: numbers
}]
};
var myChart = new Chart(ctx, {
type: 'line',
data: chartData
});
I have tried to loop the contents of the lists from my python file into different containers such as <div>, <ol> and <ul>and access those through document.getElementById("") among some other attempts, can't really remember them all.
I have tried to find the answer on google but to no avail.
Any help is appreciated and I should mention that I'm new to these coding languages and frameworks so please have some oversight if what I am missing is obvious.
=== NEW WORKING VERSION ===
chart.html :
<script type="text/javascript">
window.addEventListener('DOMContentLoaded', (event) => {
const myChart2 = document.getElementById('ChartOne');
drawChart(ChartOne, {{ labels| tojson }}, {{ values| tojson }}, ChartType.LINE);
});
</script>
<div>
<canvas id="ChartOne" width="800" height="400"></canvas>
<p id="caption">line chart displaying labels n' values</p>
</div>
script.js:
const ChartType = {
LINE: "line" // add more variables for more chart options
}
function drawEmployeeChart(ctx, labels, values, chartType) {
var chartData = {
labels: labels,
datasets: [{
label: 'values',
data: values,
}]
};
var myChart = new Chart(ctx, {
type: chartType,
data: chartData
});
}
Now that you've separated your javascript into a new js file, you have to get your variables there.
What you could do is define a javascript function in your .js file that takes two arrays:
function render_chart(labels, values)
{
var ctx = document.getElementById('myChart');
var chartData = {
labels: names,
datasets: [{
label: 'values',
data: values
}]
};
var myChart = new Chart(ctx, {
type: 'line',
data: chartData
});
}
Then call the function from your chart.html page, but you have to convert the variables you pass from Flask to json. To do that do this, using the special tojson Jinja2 filters:
<script type="text/javascript">render_chart({{ labels|tojson }}, {{ values|tojson }})'></script>

ChartJs - displaying data dynamically from back-end

I have been struggling with this one for days now, really need some help. I need to apply gradient colors and some custom styling to our ChartJs bar chart, that contains call reporting data which comes from the back-end server. I found a way how to apply the styles and gradients, but can't figure out how to configure datasets to display correct data from the server, instead of some random numbers (eg. 10,20,30), like I tried for gradientGreen below. Any ideas?
//main html
<div class="row mb-4 mt-4">
<div class="col-9">
<h4 class="text-center">Call Distribution</h4>
#await Component.InvokeAsync("HourlyCallTotals", new { from = Model.From, to = Model.To, customer = Model.customer, site = Model.site })
</div>
//component html
#model CallReporter.ViewModels.BasicFilter
<div id="hourlyChart">
</div>
<script>
var HourlyCallData = #Html.RenderAction("HourlyTotals", "Calls", "", new { from = Model.from.ToString("s"), to = Model.to.ToString("s"), customer = Model.customer, site = Model.site })
</script>
//relevant part of JS function for Chart
function hoursChartAjax() {
var hourlyChart = $('#hourlyChart').html('<canvas width="400" height="300"></canvas>').find('canvas')[0].getContext('2d');
// set gradients for bars
let gradientGreen = hourlyChart.createLinearGradient(0, 0, 0, 400);
gradientGreen.addColorStop(0, '#66d8b0');
gradientGreen.addColorStop(1, '#1299ce');
let gradientBlue = hourlyChart.createLinearGradient(0, 0, 0, 400);
gradientBlue.addColorStop(0, '#1299ce');
gradientBlue.addColorStop(1, '#2544b7');
if (hourlyChart !== undefined) {
$.get(base + "Calls/HourlyTotals", { from: from.format(), to: to.format(), customer: currentCustomer.id, site: currentSite }, function (data) {
// set the default fonts for the chart
Chart.defaults.global.defaultFontFamily = 'Nunito';
Chart.defaults.global.defaultFontColor = '#787878';
Chart.defaults.global.defaultFontSize = 12;
var chart = new Chart(hourlyChart, {
type: 'bar',
data: {
labels: ['6AM', '9AM', '12AM', '3PM', '6PM', '9PM', '12PM'],
datasets: [
{
label: 'Total outgoing calls',
backgroundColor: gradientBlue,
data: HourlyCallData
},
{
label: 'Total incoming calls',
backgroundColor: gradientGreen,
data: [10, 20, 30]
}
]
},
//relevant part of back-end code that returns call data as Json
totalsContainer.Totals = allCallsHourly.OrderBy(x => x.Date).ToList();
return Json(new
{
labels = totalsContainer.Totals.Select(x => x.Date.ToString("hh tt")),
datasets = new List<object>() {
new { label = "Total Outgoing Calls", backgroundColor = "#1299CE", data = totalsContainer.Totals.Select(x => x.TotalOutgoingCalls) },
new { label = "Total Incoming Calls", backgroundColor = "#00B050", data = totalsContainer.Totals.Select(x => x.TotalIncomingCalls) } }
});
Attached img with console log and error, after trying solution below:
If the data comes formatted in the right way, you can just write this:
var chart = new Chart(hourlyChart, {
type: 'bar',
data: data: data
}
If not you could do it like so:
var chart = new Chart(hourlyChart, {
type: 'bar',
data: {
labels: data.labels,
datasets: [
{
label: data.datasets[0].label,
backgroundColor: gradientBlue,
data: data.datasets[0].data
},
{
label: data.datasets[1].label,
backgroundColor: gradientGreen,
data: data.datasets[1].data
}
]
}
}

Use a JS string variable passed in as a parameter as the value of a data parameter in chart.js?

This is the relative Javascript that is not working quite right. The parameter thisChartData is a string and it alerts just fine; it's generated by a PHP script elsewhere (but that's not important).
If I copy and paste what the alert output into the data section the chart generates fine. But for some reason I can't use the parameter name in the data section
function drawChart( thisChartData, thisChartTitle ) {
var ctx = $("#my-chart");
alert(thisChartData); // alerts-> '131', '1043', '144', '43'
//chart data
var ctxData = {
datasets: [{
data: [ thisChartData ], //using the paramter variable doesn't work
backgroundColor: [ <?php echo $bg_color_list; ?> ]
}]
};
Meanwhile the code below works fine, I need the data to be variable depending on what I pass to the function because I'm going to have several data sets I want to scroll through.
function drawChart( thisChartData, thisChartTitle ) {
var ctx = $("#my-chart");
alert(thisChartData); // alerts-> '131', '1043', '144', '43'
//chart data
var ctxData = {
datasets: [{
data: [ '131', '1043', '144', '43' ],
backgroundColor: [ <?php echo $bg_color_list; ?> ]
}]
};
data: [ thisChartData ] should just be data: thisChartData, and when you call drawChart, pass in an array. E.g.:
function drawChart( thisChartData, thisChartTitle ) {
var ctx = $("#my-chart");
//chart data
var ctxData = {
datasets: [{
data: thisChartData, // <======
backgroundColor: [ <?php echo $bg_color_list; ?> ]
}]
};
and
drawChart(['131', '1043', '144', '43'], "title");

Categories