I was hoping someone could help me with my code. I've modified the example from fiddle so that it works with Django web framework, but I can't seem to debug it since it doesn't throw any exception, but the chart doesn't render neither. It's very weird. Essentially, I am redirecting the json datasource to read my own local data.
So far, I have the following code in home.html:
<script src="/static/js/jquery-2.1.0.min.js"></script>
<script src="/static/js/stock/highstock.js"></script>
<script src="/static/js/stock/modules/exporting.js"></script>
<div id="stock_panel" class="stock-body" style="width:100%;height:314px"></div>
<script type="text/javascript">
$(function(){
var chartDataUrl = "{% url 'chartFishPrice' %}";
$.getJSON(chartDataUrl,
function(data) {
// Create the chart
$('#stock_panel').highcharts('StockChart', {
rangeSelector : {
selected : 1,
inputEnabled: $('#stock_panel').width() > 480
},
title : {
text : 'fish Price'
},
series : [{
name : 'chart_data',
data : data,
tooltip: {
valueDecimals: 2
}
}]
});
});
});
</script>
And this is views.py:
def chartFishPrice(request):
ff = FishCaught.objects.filter(fish_id=1)
data = {'dates': [], 'values': []}
for f in ff:
data['dates'].append(int(f.date_caught.strftime("%s")))
data['values'].append(int(f.num_caught))
data2 = {}
data2['chart_data'] = data
print data2
return HttpResponse(json.dumps(data2), content_type='application/json')
and the urlpatterns:
url(r'^chartFishPrice/$', 'fish.views.chartFishPrice', name='chartFishPrice'),
And I've double checked my data format in json as:
{"chart_data": {"dates": [1396310400, 1396396800, 1396483200, 1396569600], "values": [2, 3, 2, 4]}}
and for comparison, this is the sample data from the example:
[
/* May 2006 */
[1147651200000,67.79],
[1147737600000,64.98],
[1147824000000,65.26]]
This is weird stuff. I really appreciate any help you can spare. Thanks.
But that data doesn't seem to be in the same format at all. You have an object consisting of two arrays, one of "dates" and one of "values". The sample data has an array of arrays, with each sub-array consisting of a single date and a single value.
If you want the same format as the sample, your view should look like this:
data = []
for f in ff:
date = int(f.date_caught.strftime("%s"))
value = int(f.num_caught)
date.append([date, value])
Related
i'm trying to display data on my charts using some model values and charts.js. My values are a country field and a class method that i'm not sure how I'm to call it.
I keep getting the error
"TypeError: 'Organization' object is not subscriptable django
charts.js" or nothing displays at all. Please help.
models.py
from django_countries.fields import CountryField
class Organization(models.Model):
country = CountryField(blank_label='(select country)')
def Total_Score(cls):
Total_Score = cls.grants_score() + cls.internal_score() #This is a sum of other class methods. This part works as is.
return Total_Score
Views.py
def scores_charts(request):
labels = []
data = []
orgz = Organization.objects.values('country').annotate(Total_Scores=Organization.objects.values('Total_Scores()'))
for org in orgz:
labels.append(org['country'])
labels.append(org['Total_Scores'])
return JsonResponse(data={
'labels': labels,
'data': data,
})
Template.html
<div class="card-block-big">
<canvas id="scores_charts" data-url="{% url 'scores_charts' %}"></canvas>
</div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.3/dist/Chart.min.js"></script>
<script>
$(function () {
var $scores_charts = $("#scores_charts");
$.ajax({
url: $scores_charts.data("url"),
success: function (data) {
var ctx = $scores_charts[0].getContext("2d");
new Chart(ctx, {
type: 'bar',
data: {
labels: data.labels,
datasets: [{
label: 'Scores',
backgroundColor: 'blue',
data: data.data
}]
},
options: {
responsive: true,
legend: {
position: 'top',
},
title: {
display: true,
text: 'Scores Bar Chart'
}
}
});
}
});
});
</script>
This error
"TypeError: 'Organization' object is not subscriptable django charts.js"
suggests that you are trying to get an element out of an Organization object that isn't a dictionary, list, or a tuple.
I suspect the likely cause of this may be stemming from the following (though you can confirm this with the full error trace which should tell you the line of code that is causing the error):
for org in orgz:
labels.append(org['country'])
labels.append(org['Total_Scores'])
You should try to debug the values of this and verify that they are correct.
I'm trying to integrate charts.js charts with django. So far im able to display the pie chart. But the problem im facing is in the bar chart or charts such as where i have not just x and y but x, y1, y2, y3 etc. I'm unable to find the syntax for passing the data to the template
Here's my Model
class due(models.Model):
months= models.CharField(max_length=30)
paid = models.PositiveIntegerField()
unpaid = models.PositiveIntegerField()
def __str__(self):
return "{}-{}".format(self.months, self.paid,self.unpaid)
Here's my View
def graph2(request):
labels = []
data = []
queryset = due.objects.order_by('-paid')[:10]
for Due in queryset:
labels.append(Due.name)
data.append(Due.paid,Due.unpaid)
return render(request, 'account/graph1.html', {
'labels': labels,
'data': data,
})
And this is where i want to access the data from my view, how do i replace the both data fields with my paid and unpaid fields from views. I know the data: {{ data|safe }} this is the syntax but it gets only one column. How do i get y1, y2, y3 etc.
<script>
new Chart(document.getElementById("bar-chart-grouped"), {
type: 'bar',
data: {
labels: ["1900", "1950", "1999", "2050"],
datasets: [
{
label: "Africa",
backgroundColor: "#3e95cd",
data: [133,221,783,2478]
}, {
label: "Europe",
backgroundColor: "#8e5ea2",
data: [408,547,675,734]
}
]
},
options: {
title: {
display: true,
text: 'Population growth (millions)'
}
}
});
</script>
Try to debug your code in the view.py file, by adding print() functions, to see if everything in the business logic works correctly. Also, a note: I do not see any variables ({{ }}) referenced in your template. That means you do not access them inside of it. Please let me know if I helped you, and if I understood your question correctly.
Problem is to show two series, for adjusted high and adjusted low, in a highcharts highstock graph similar to the following which shows only one series:
Links to similar Highstock question and JSFiddle:
https://forum.highcharts.com/viewtopic.php?f=12&t=40964&p=142595&hilit=multiple+series#p142595
https://jsfiddle.net/BlackLabel/xqgv2b4k/
Below are my working files used to produce the graph above.
sample.csv (input)
DATE,ADJ_HIGH,ADJ_LOW
2018-04-27,164.33,160.630
2018-04-30,167.26,161.840
2018-05-01,169.20,165.270
2018-05-02,177.75,173.800
2018-05-03,177.50,174.441
csv_to_json_testing.py
import numpy as np
import pandas as pd
input_file = 'sample.csv'
df = pd.read_csv(input_file, usecols=[0,1,2], parse_dates=['DATE'], date_parser = pd.to_datetime) # keep_default_na = False
with open('overflow.txt', 'w') as f:
df['DATE'] = df['DATE'].values.astype(np.int64) // 10 ** 6
print(file=f)
print('DATE, ADJ_HIGH (json)', file=f)
print(file=f)
print(df[['DATE','ADJ_HIGH']].tail(5).to_json(orient='values'), file=f)
print(file=f)
print('DATE, ADJ_LOW (json)', file=f)
print(file=f)
print(df[['DATE','ADJ_LOW']].tail(5).to_json(orient='values'), file=f)
print(file=f)
print('DATE, ADJ_HIGH, ADJ_LOW (json)', file=f)
print(file=f)
print(df[['DATE','ADJ_HIGH','ADJ_LOW']].tail(5).to_json(orient='values'), file=f)
overflow.txt (output)
DATE, ADJ_HIGH (json)
[[1524787200000,164.33],[1525046400000,167.26],[1525132800000,169.2],[1525219200000,177.75],[1525305600000,177.5]]
DATE, ADJ_LOW (json)
[[1524787200000,160.63],[1525046400000,161.84],[1525132800000,165.27],[1525219200000,173.8],[1525305600000,174.441]]
DATE, ADJ_HIGH, ADJ_LOW (json)
[[1524787200000,164.33,160.63],[1525046400000,167.26,161.84],[1525132800000,169.2,165.27],[1525219200000,177.75,173.8],[1525305600000,177.5,174.441]]
sample.json (DATE, ADJ_HIGH)
[[1524787200000,164.33],[1525046400000,167.26],[1525132800000,169.2],[1525219200000,177.75],[1525305600000,177.5]]
highstock_test.html
<html>
<head>
<title>
Chart
</title>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<script src="https://code.highcharts.com/stock/modules/export-data.js"></script>
<script type="text/javascript">
$.getJSON('sample.json', function (data) {
// Create the chart
Highcharts.stockChart('container', {
rangeSelector: {
selected: 1
},
title: {
text: 'XYZ Stock Price'
},
series: [{
name: 'XYZ',
data: data,
tooltip: {
valueDecimals: 2
}
}]
});
});
</script>
</head>
<body>
<div id="container" style="width: 400px; height: 350px; margin: 0 auto"></div>
</body>
</html>
When I store sample.json and highstock_test.html in a folder, then open the html file in a browser, I get the highstock graph shown above for one series. My challenge is to properly populate and format sample.json with DATE, ADJ_HIGH, and ADJ_LOW data, and to edit highstock_test.html so the plot properly renders two series instead of one. Would like to use the method that is easiest to understand and that could also be adapted to serve charts from a flask application.
To display two series you need to create two series configuration objects:
Highcharts.stockChart('container', {
series: [{
data: data1
}, {
data: data2
}]
});
If you want to use two separate JSON data, you will only have to assign the right values: http://jsfiddle.net/BlackLabel/fho6na5r/, but to use only one, you need to convert it to data structure required by Highcharts:
var data = [
[1524787200000, 164.33, 160.63],
[1525046400000, 167.26, 161.84],
[1525132800000, 169.2, 165.27],
[1525219200000, 177.75, 173.8],
[1525305600000, 177.5, 174.441]
],
dataS1 = [],
dataS2 = [];
data.forEach(function(el) {
dataS1.push([el[0], el[1]]);
dataS2.push([el[0], el[2]]);
});
Highcharts.stockChart('container', {
series: [{
data: dataS1
}, {
data: dataS2
}]
});
Live demo: http://jsfiddle.net/BlackLabel/gv7mph8x/6/
I'm passing a 2-dimensional array of float values to my views.py via ajax. My ajax call looks like this:
$.ajax({
method: "POST",
url: "introURL",
data: {
csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
dsg_mtx : JSON.stringify(dsg_mtx),
},
success: function(data) {
document.getElementById("test").innerHTML = data; // echo response
},
error: function() {
alert ("Something went wrong");
}
I'm pulling my data to the view with this call:
def introURL(request):
if request.is_ajax():
try:
designMtx = json.loads(request.POST['dsg_mtx'], parse_float=None)
except KeyError:
return HttpResponse('Error, intro import')
... Some transformation of designMtx...
return HttpResponse(response)
else:
raise Http404
so my question is how do I convert this json stringify'd object back to a 2-dimensional array which I can use to compute a response? As you can see I tried using the parse_float option, but it's still a str data type.
the array being passed, dsg_mtx, is created with a Handson tables and looks like this:
-1 -1
-1 1
1 -1
1 1
Thanks for your guidance.
My issue turned out to be the default settings for handsontable. while I was supplying the table with float values, by default, the table was converting them to strings. so I was posting a matrix of strings that looked like float. the fix was simply to reformat the handsontable cells where the data was placed.
var data = function () {
return Handsontable.helper.createSpreadsheetData(mtxrows, mtxcols);
};
var hot = new Handsontable(container, {
data: data,
height: 480,
colHeaders: true,
rowHeaders: true,
stretchH: 'none',
columnSorting: true,
contextMenu: true,
className: "htCenter",
cells: function (row, col, prop) {
var cellProperties = {};
if (row > 0) {
cellProperties.type = 'numeric';
cellProperties.format = '0[.]000';
}
return cellProperties;
},
afterChange: function () {
var tmpData = JSON.parse(JSON.stringify(mtx_data));
}
});
So basically anything after the first row is set to numeric type.
so now this line in my ajax call:
dsg_mtx : JSON.stringify(dsg_mtx),
formats it correctly and views.py uses this call to load it in properly:
designMtx = json.loads(request.POST['dsg_mtx'])
Thanks to Tomasz Jakub for suggesting the console.log() which helped me diagnose the issue.
Regards,
Jaime
Try json.loads but in parse_float pass decimal.Decimal
designMtx = json.loads(request.POST['dsg_mtx'], parse_float=decimal.Decimal)
I'm trying to learn django/python and I'm trying to figure out how to read json data...
I have something like :
{
region: {
span: {
latitude_delta: 0.08762885999999526,
longitude_delta: 0.044015180000002374
},
center: {
latitude: 37.760948299999995,
longitude: -122.4174594
}
},...
}
I'm trying to read specific data in my html page. Right now this json data is being displayed in the html page.
The source of the this json comes from this:
return HttpResponse(json.dumps(response),mimetype="application/json")
I'm trying to figure out the django/python convention of getting specific data? Am I supposed to do a for each loop? I come from a self taught php background, and I'm trying to teach myself python/django.
Thank you
edit:
I also have this in my view.py before the return HttpResponse
try:
conn = urllib2.urlopen(signed_url, None)
try:
response = json.loads(conn.read())
finally:
conn.close()
except urllib2.HTTPError, error:
response = json.loads(error.read())
This is the easiest way to read json in html (Send by Django)
def sendJson(request):
if request.method == 'GET':
context = {"name":"Json Sample Data"}
return render_to_response('name.html',context)
Django Template Html Code
<div class="col-md-9 center">
<span class="top-text">{{name}}</span>
</div>
Now according to your:
def sendJson(request):
if request.method == 'GET':
jsonData = {
region: {
span: {
latitude_delta: 0.08762885999999526,
longitude_delta: 0.044015180000002374
},
center: {
latitude: 37.760948299999995,
longitude: -122.4174594
}
}
}
data = json.dumps(jsonData)
return HttpResponse(data, content_type="application/json")
you can read this data by using jquery also
another example to create json and read in html
url.py
url(r'^anotherexample/$', 'views.anotherexample', name="anotherexample"),
view.py
def anotherexample(request):
if request.method == 'POST':
_date = strftime("%c")
response_data = {}
response_data['status'] = 'taken'
response_data['issueTakenTime'] = _date
return HttpResponse(json.dumps(response_data), content_type="application/json")
Html view and jquery
$.ajax({
url: "/anotherexample/",
// contentType: "application/json; charset=UTF-8",
data: { csrfmiddlewaretoken: "{{ csrf_token }}", // < here
status : "taken"
},
type: "POST",
error: function(res) {
console.log("errr", res)
},
success: function(res) {
console.log("res", res)}
})
It's not clear what you want to loop over, where, or how, but basic loops work like this:
data = {"key1":[1,2], "key":[4,5]}
for key, values in data.iteritems():
print key, values
I was able to figure out the solution through this link: Decode json and Iterate through items in django template
It helped me and hopefully it'll help someone else who has the same problem as me.
Thanks