I have a django template that looks like this:
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" type="text/javascript"></script>
<script src="{{ STATIC_URL }}js/jquery.flot.js"></script>
<!--<script src="c:/src/project/scraper/collegedata/templates/chart.js" type="text/javascript"></script>-->
<script src="{{ STATIC_URL }}js/chart.js" type="text/javascript"></script>
</head>
<body>
<div id="chart1" style="width:600px;height:300px"></div>
<script>
show_graph("{{ chart_type }}", {{ series_names }}, {{ data }}, {{ answer }});
</script>
<form action="start">
<input type="submit" value="Back to Questions" />
</form>
</body>
</html>
where show_graph is a function in chart.js. However, pycharm gives me one of two errors, either:
unresolved function or method show_graph(), or
invalid number of parameters passed: expected 4
and the function is clearly not being called.
I'm a little confused as to whether or not I can even pass template vars to a js function at all...
Does anyone have any insight?
EDIT:
this generates
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" type="text/javascript"></script>
<script src="/static/js/jquery.flot.js"></script>
<!--<script src="c:/src/project/scraper/collegedata/templates/chart.js" type="text/javascript"></script>-->
<script src="/static/js/chart.js" type="text/javascript"></script>
</head>
<body>
<div id="chart1" style="width: 600px; height: 300px;"></div>
<script>
show_graph("pie", [<ResponseOption: puddentane>, <ResponseOption: down the lane>], [1, 0], 0);
</script>
<form action="start">
<input value="Back to Questions" type="submit">
</form>
</body></html>
where chart.js looks like (values temporarily hardcoded for troubleshooting, and it should be mentioned that $.plot also gives an unresolved function error):
function show_graph(charttype, series_names, data, answer_index){
var data = [2000, 50, 400, 200, 5000];
var data3 = [
{ label: "my cat", data: 10, color: 'rgb(85, 96, 42)'},
{ label: "my friends", data: 20, color: 'rgb(105, 118, 52)'},
{ label: "my boyfriend", data: 30, color: 'rgb(125, 141, 62)'},
{ label: "my job", data: 30, color: '#42215F'},
{ label: "food", data: 10, color: 'rgb(145, 164, 72)'},
{ label: "social skills", data: 0, color: 'rgb(166, 189, 82)'}
];
alert("in chart.js");
var charttype = "pie";
var type = {};
type[charttype] = {show: true};
var chart_options = {};
chart_options["series"]=type;
var plot = $.plot($("#chart1"), data3, chart_options);
}
It looks like series_names is just being output as the HTML entities of an object without a proper __unicode__ method. You're getting:
show_graph("pie", [<ResponseOption: puddentane>,
Which, decoded, is:
show_graph("pie", [<ResponseOption: puddentane>, ...
What actually needs passing to the method? You probably need to think about how you want {{ series_names }} to be output, rather than just calling the string representation of that variable. What you're generating at the moment is invalid Javascript - the console of your browser will probably reinforce this point.
Invalid number of parameters means one of your context variables, probably answer, was blank.
Your code is risky because Django will escape your context variables to be HTML safe, not JavaScript safe. One trick I use to get around this is to put all the parameters to a JS function in a dictionary, then convert it to JSON and use that for the context variable (using it with the |safe filter, and the <![CDATA[ markup in the template if needed).
As for show_chart not being resolved, you might want to make sure chart.js really is being loaded, and that it's not in a namespace of some form.
Related
I am stuck into a problem, I want to pass django variable to javascripts but I can't.
views.py
def dashboard_view(request):
months_before = 5
now = datetime.utcnow()
from_datetime = now - relativedelta(months=months_before)
modified_from_datetime = from_datetime.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
month = Btdetail.objects.filter(DatePur__gte=modified_from_datetime).count()
return render(request, "dashboard.html", {'month': month})
I want to embed month value to javascripts data
my html script function is
<script>
var xValues = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
new Chart("myChart3", {
type: "line",
data: {
labels: xValues,
datasets: [{
data: [5,10,20,15,20,5,15,40,10,12,24,35],
borderColor: "red",
fill: false
}]
},
options: {
legend: {display: false}
}
});
</script>
actually I want to create a Area bar, all things are good but javascript functions cant get value from django database and if there is another way to do this please tell me
[1]: https://i.stack.imgur.com/9bJzE.jpg
on your anypage.html inside <body> </body> tag
<body>
<p> text for example </p>
<div> some divs </div>
<script type="text/javascript">
var month_count = {{ month }};
</script>
</body>
it will initiate month_count variable on your anypage.html and you could use it with javascripts inside this anypage.html
views.py
import json
def your_page(request):
context = {
"some_list": json.dumps([1,2,3]),
}
return render(request, "your_template.html", context)
javascript
<script>
const some_list = JSON.parse(`{{some_list|safe}}`);
</script>
Thanks for reading my post
okay, I'm currently working on Django project that displays data in a dashboard; I manage to display and draw charts with Chart JS, great but now I need to limited number data in Django database to be displayed on charts and display the most recent data put into the database.
I use Django built-in tag to display the most recently is "last" and limiting the display data, the tag is "length_is"(Solve).
Here are my HTML codes for using the "last" tag and index page
<div class = "containor">
<div class = "float-right my-4 chartjs-render-monitor" id="chartContainerPH" style="width: 49%; height: 400px;display: inline-block; background-color:#FDFDFD;">
<center>
<a class="title-link" href="{%url 'ph' %}">PH:</a>
<p>{% for tank_system in tank %} {{tank_system.ph|last}} {%endfor%}</p>
</center>
{%include 'FrounterWeb/includes/PHchart.html'%}
</div>
This is the result I get Last Tag result in my index
(Solve)
Here' my code for chart HTML which I use the length_is tag
{%block PHchart%}
<canvas class = "my-4 chartjs-render-monitor" id="PHchart" ></canvas>
<script>
var ctx = document.getElementById("PHchart");
var PHchart = new Chart(ctx, {
type: 'line',
data: {
labels: [ {%for tank_system in tank%} "{{tank_system.datetime}}", {%endfor%} ], //x-Axis
datasets: [{ //y-Axis
label: 'PH1',
data: [ {%for tank_system in tank%} {{tank_system.PH|length_is:"3"}}, {%endfor%} ],
backgroundColor: "rgb(249, 24, 24,0.2)",
borderColor: "rgb(249, 24, 24,0.2)",
fill: true,
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:false
}
}]
}
}
});
</script>
</div>{%endblock%}
and the result Length_is on chart
Summary: I can't get the built-in "filter" and "length_is"(Solve) Django tags to work. Could you please share an example or tutorial with me? The Django documentation didn't write many examples.
and here my views codes;
#login_required(login_url='/accounts/login/')
def index(request):
tank = tank_system.objects.all()
args = {'tank':tank}
return render(request,'FrounterWeb/extends/includes.html',args)
and my models' codes;
class tank_system(models.Model):
PH = models.DecimalField(max_digits=3, decimal_places=1)
EC = models.DecimalField(max_digits=3, decimal_places=1)
WaterLevel = models.IntegerField(default=100)
TempWater = models.IntegerField(default=0)
TempRoom = models.IntegerField(default=0)
datetime = models.DateTimeField(default=timezone.now())
Both of these filters are well documented in the django docs. The last filter gets you the last element of a list, and the length_is filter returns True if the list is that length, or False otherwise.
This likely means that there is an issue in your understanding of your code. You'll want to verify the type and the values of tank_system.PH or tank_system.ph (you have both) and the case will matter. One way to debug this is to simply output the value of tank_system.ph to the web page and verify the result.
This question already has an answer here:
updating high chart on real time in angular js after a particular time
(1 answer)
Closed 5 years ago.
I'm using angular-chart.js to create a chart using the example code below. This works but I'd like to create a chart dynamically using AJAX. If I insert the chart using AJAX the chart does not load. I would like to know how I can change the below code to allow me to dynamically create an Angular Chart using AJAX?
Example HTML file
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.js"></script>
<script src="https://cdn.rawgit.com/jtblin/angular-chart.js/0.8.8/dist/angular-chart.min.js"></script>
<link rel="stylesheet" href="https://cdn.rawgit.com/jtblin/angular-chart.js/0.8.8/dist/angular-chart.min.css"></link>
</head>
<body>
<!-- If I try to insert the below using AJAX the chart does not load -->
<div ng-app="app">
<div ng-controller="ChartController as vm">
<canvas id="bar" class="chart chart-bar" chart-data="vm.barChart.data" chart-labels="vm.barChart.labels"></canvas>
</div>
</div>
<script>
angular
.module('app', ['chart.js'])
.controller('ChartController', ChartController);
function ChartController() {
var vm = this;
// Data
vm.barChart = {
labels: ['2006', '2007', '2008', '2009', '2010', '2011', '2012'],
series: ['Series A', 'Series B'],
data: [
[65, 59, 80, 81, 56, 55, 40],
[28, 48, 40, 19, 86, 27, 90]
]
};
}
</script>
</body>
</html>
Update: My question is marked as duplicate but I'm sure this is different as I'm asking how to 'create' not 'update' a chart after the DOM has already been loaded. I think I should have been more clear, I'm not asking how to update the chart data using AJAX, I'm asking how to actually 'create' the chart using AJAX. I can only seem to create the chart when DOM loads for the first time, not after.
In AngularJS, you could to use Services.
AngularJS services are substitutable objects that are wired together
using dependency injection (DI). You can use services to organize and
share code across your app.
You can declare an AngularJS Service by this way:
.service("MyService", ["$http", function($http) {
return {
getMyData: function() { // This service method can be called from the controller.
return $http.get("https://gist.githubusercontent.com/dannyjhonston/4fade791505e812eae1a3fea2cde6ac4/raw/d73d8eb12cff8911b6b7c681718a760129ae1299/angular-chart-data.json", null, {
responseType: "json"
});
}
};
}])
Where:
"MyService": Service name. You can inject this service through this name to the AngularJS Controller.
"$http": $http: A core AngularJS service that facilitates communication with the remote HTTP servers via the browser's
XMLHttpRequest object or via JSONP. The $http service is a
function which takes a single argument that is used to generate an
HTTP request and returns a promise.
Inject the AngujarJS Service in the AngularJS Controller:
.controller("ChartController", ["MyService", ChartController]);
To call the AngularJS Service method from the AngularJS Controller and handle the received data, you could use this:
MyService.getMyData().then(function(response) {
// Data.
vm.barChart = response.data;
}, function(response) {
console.log("Error: " + response);
});
AJAX requires an URL that could return a JSON object, in this case.
URL: https://gist.githubusercontent.com/dannyjhonston/4fade791505e812eae1a3fea2cde6ac4/raw/d73d8eb12cff8911b6b7c681718a760129ae1299/angular-chart-data.json
JSON:
{
"labels": ["2006", "2007", "2008", "2009", "2010", "2011", "2012"],
"series": ["Series A", "Series B"],
"data": [
[65, 59, 80, 81, 56, 55, 40],
[28, 48, 40, 19, 86, 27, 90]
]
}
See this example:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.js"></script>
<script src="https://cdn.rawgit.com/jtblin/angular-chart.js/0.8.8/dist/angular-chart.min.js"></script>
<link rel="stylesheet" href="https://cdn.rawgit.com/jtblin/angular-chart.js/0.8.8/dist/angular-chart.min.css">
</head>
<body>
<div ng-app="app">
<div ng-controller="ChartController as vm">
<canvas id="bar" class="chart chart-bar" chart-data="vm.barChart.data" chart-labels="vm.barChart.labels"></canvas>
</div>
</div>
<script>
angular
.module("app", ["chart.js"])
.service("MyService", ["$http", function($http) {
return {
getMyData: function() {
return $http.get("https://gist.githubusercontent.com/dannyjhonston/4fade791505e812eae1a3fea2cde6ac4/raw/d73d8eb12cff8911b6b7c681718a760129ae1299/angular-chart-data.json", null, {
responseType: "json"
});
}
};
}])
.controller("ChartController", ["MyService", ChartController]);
function ChartController(MyService) {
var vm = this;
MyService.getMyData().then(function(response) {
// Data.
vm.barChart = response.data;
}, function(response) {
console.log("Error: " + response);
});
}
</script>
</body>
</html>
Hope this helps.
Here is a way to get chart data dynamically via ajax.
Key is to set the data property of your chart via another function.
To get data via ajax it makes sense to put this functionality into it's own service and link this service to the controller.
the getData() function of the service can be triggered anytime by buttons or periodically via timers ($timeout)
In this example I used an external file called data.json with the following content:
[
[65, 59, 80, 81, 56, 55, 40],
[28, 48, 40, 19, 86, 27, 90]
]
Happy coding!
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.js"></script>
<script src="https://cdn.rawgit.com/jtblin/angular-chart.js/0.8.8/dist/angular-chart.min.js"></script>
<link rel="stylesheet" href="https://cdn.rawgit.com/jtblin/angular-chart.js/0.8.8/dist/angular-chart.min.css"></link>
</head>
<body>
<!-- If I try to insert the below using AJAX the chart does not load -->
<div ng-app="app">
<div ng-controller="ChartController as vm">
<canvas id="bar" class="chart chart-bar" chart-data="vm.barChart.data" chart-labels="vm.barChart.labels"></canvas>
</div>
</div>
<script>
angular
.module('app', ['chart.js'])
.service('ChartService', ['$http', ChartService])
.controller('ChartController', ['ChartService', ChartController]);
function ChartService($http) {
this.getData = function (callback) {
$http.get('data.json').success(function(response) {
console.log("Got data: " + response);
if (callback) callback(response);
});
};
}
function ChartController(chartService) {
var vm = this;
// Data
vm.barChart = {
labels: ['2006', '2007', '2008', '2009', '2010', '2011', '2012'],
series: ['Series A', 'Series B'],
data: []
};
function callback(data) {
vm.barChart.data = data;
}
chartService.getData(callback);
}
</script>
</body>
</html>
I'm trying to return a JSON list in my controller. Not sure where I am going wrong. Any help would be greatly appreciated. I am trying to implement a grid a found online.
Here is my controller:
//[HttpPost]
public JsonResult JqueryTest()
{
var estimateDetails = db.EstimateDetail
.Include(x => x.EstimationItem)
.Include(x => x.EstimateHeader);
return Json(estimateDetails, JsonRequestBehavior.AllowGet);
}
Here is my view:
#model IEnumerable < EstimationTools.Models.Entities.EstimateDetail >
ViewBag.Title = "JqueryTest";
}
<h2>JqueryTest</h2>
<html lang="en">
<head>
<!-- The jQuery library is a prerequisite for all jqSuite products -->
<script type="text/ecmascript" src="../../../js/jquery.min.js"></script>
<!-- We support more than 40 localizations -->
<script type="text/ecmascript" src="../../../js/trirand/i18n/grid.locale-en.js"></script>
<!-- This is the Javascript file of jqGrid -->
<script type="text/ecmascript" src="../../../js/trirand/jquery.jqGrid.min.js"></script>
<!-- This is the localization file of the grid controlling messages, labels, etc.
<!-- A link to a jQuery UI ThemeRoller theme, more than 22 built-in and many more custom -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<!-- The link to the CSS that the grid needs -->
<link rel="stylesheet" type="text/css" media="screen" href="../../../css/trirand/ui.jqgrid-bootstrap.css" />
<script>
$.jgrid.defaults.width = 780;
$.jgrid.defaults.styleUI = 'Bootstrap';
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<meta charset="utf-8" />
<title>jqGrid Loading Data - JSON</title>
</head>
<body>
<div style="margin-left:20px">
<table id="jqGrid"></table>
<div id="jqGridPager"></div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#jqGrid").jqGrid({
url: 'EstimationTool/plugins/jqGrid',
datatype: "json",
colModel: [
{ label: 'Estimate', name: 'Estimate', width: 75 },
{ label: 'Contingency', name: 'Contingency', width: 90 },
{ label: 'Comment', name: 'Comment', width: 100 },
{ label: 'Subactivity', name: 'EstimationItem.Subactivity', width: 100 },
{ label: 'EstimationArea', name: 'EstimationItem.Area.EstimationArea', width: 100 },
{ label: 'Description', name: 'EstimationItem.GeneralActivity.Description', width: 100 }
// sorttype is used only if the data is loaded locally or loadonce is set to true
],
viewrecords: true, // show the current page, data rang and total records on the toolbar
width: 780,
height: 200,
rowNum: 30,
loadonce: true, // this is just for the demo
pager: "#jqGridPager"
});
});
</script>
</body>
</html>
First thing first... as stephen.vakil states, there is an error in your url, as you are pointing to an action so called "jqGrid":
url: 'EstimationTool/plugins/jqGrid'
The usual syntax is: '{Controller}/{Action}/'
Which in your case, the action name is "JqueryTest" as stated above. So, I don't know the name of your Controller, but I hope you've got the idea. Something like this:
url: 'YourController/JqueryTest'
On the other hand, within your Action, you should return a list instead... so, just add .ToList() at the end of the query or append it to your parameter:
return Json(estimateDetails.**ToList()**, JsonRequestBehavior.AllowGet);
Regards,
I created a funnel chart in java script . And converted into angular And now I'm trying to use the http.get method in angular to fetch the json data. And I'm stuck here and got confused in this part
And now let me show u my code part
---index.html---
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>FusionCharts - Funnel 3D Chart</title>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<link rel="stylesheet" type="text/css" href="/css/normalize.css">
<script data-require="angular.js#1.4.0-beta.6" data-semver="1.4.0-beta.6" src="https://code.angularjs.org/1.4.0-beta.6/angular.js"></script>
<script type='text/javascript' src="http://static.fusioncharts.com/code/latest/fusioncharts.js"></script>
<script type='text/javascript' src="http://static.fusioncharts.com/code/latest/fusioncharts.widgets.js"></script>
<script type='text/javascript' src='/js/lib/dummy.js'></script>
<script type='text/javascript' src="http://static.fusioncharts.com/code/latest/themes/fusioncharts.theme.fint.js"></script>
<script src="practice.js"></script>
</head>
<body ng-app="myApp">
<!-- A funnel 3D Chart showing a conversion analysis in percentage of visiting to purchase in Harry's Supermart website last year
Attribute :
# showPercentValues - set to 1 to show the values in percentage.
-->
<div id="chart-container" ng-controller="ParentCtrl" ng-init='load()' ng-model="dataSource1">FusionCharts will render here</div>
</body>
</html>
---script.js---
// Code goes here
//creating an application module
var myApp = angular.module("myApp", []);
//The below code will read the data from student.json file and will pass to the $scope variable
myApp.controller("ParentCtrl", function($scope, $http)
{
$scope.load = function(){
//alert("2");
FusionCharts.ready(function () {
//alert("1");
var conversionChart = new FusionCharts({
type: 'funnel',
renderAt: 'chart-container',
width: "100%",
dataFormat: 'json',
dataSource : "dataSource1"
});
$http.get('chart.json') //reading the studentRecord.json file
.success
(function(data1){
$scope.dataSource1 = data1;// binding the data to the $scope variable
});
conversionChart.render();
});
};
});
----chart.json----
{
"chart": {
"caption": "Ensource sales report",
"subcaption": "Purchase - Conversion analysis for last year",
"decimals": "1",
"isHollow": "0",
"isSliced": "1",
"labelDistance": "15",
"plotTooltext": "Success : $percentOfPrevValue",
"theme": "fint",
"baseFontSize":"18"
},
"data":
[
{
"label": "Total",
"value": "385634"
},
{
"label": "Contacts",
"value": "175631"
},
{
"label": "Leads",
"value": "84564"
},
{
"label": "Sanctioned",
"value": "35654"
},
{
"label": "Disbursed",
"value": "12342"
}
]
}
Plunker:http:http://plnkr.co/edit/HUKvROQv8wIiFfx6uZBk?p=preview
Here i need to fetch the json data for dataSource :but not able to do that
All the script and css for the funnel chart is been included in index.html. My oly work is to fetch the json data using the http.get method.Plz help me with this
And thanks in advance ...
It seems you were just passing the incorrect param to the dataSource field. After some playing around with your plunker, instead of passing it a function where the $http call was executed, I passed it the data itself, as you can see below.
var myApp = angular.module("myApp", []);
//The below code will read the data from student.json file and will pass to the $scope variable
myApp.controller("ParentCtrl", function($scope, $http) {
$http.get('./chart.json') //reading the studentRecord.json file
.success(function(data1) {
$scope.dataSource = data1; // binding the data to the $scope variable
FusionCharts.ready(function() {
//alert("1");
var conversionChart = new FusionCharts({
type: 'funnel',
renderAt: 'chart-container',
width: "100%",
dataFormat: 'json',
dataSource: $scope.dataSource
});
conversionChart.render();
});
});
});
Notice I wrapped the code inside $http's success callback, so that we know that the data is present at the moment of rendering.
You can see the working plunker here.