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>
Related
Working on a project here where I take values from an API, using Flask. And then adding it to a chart using chart.js
I got it to work somewhat, issue I am having is that the variable I use to add the value to the chart with, but it does not change the variable, I add to the chart, whenever the value changes in the API.
Meaning:
Sell Price: 10.3
sell price change to 10.4
Sell Price: 10.3 <-- It does not change to 10.4
Here is my python code for it:
#app.route('/product/<product>')
def productPage(product):
price = []
data = requests.get(
'https://api.hypixel.net/skyblock/bazaar?key=').json()
sell = data['products'][product]['sell_summary']
for x in sell:
price.append(x['pricePerUnit'])
currentSell = data['products'][product]['sell_summary'][0]['pricePerUnit']
return render_template('product.html', product=product, price=price, currentSell=currentSell)
#app.route('/graph_update/<product>', methods=['GET', 'POST'])
def graph_update(product):
data = requests.get(
'https://api.hypixel.net/skyblock/bazaar?key=').json()
currentSell = data['products'][product]['sell_summary'][0]['pricePerUnit']
return jsonify('', render_template('graph_update.html', currentSell=currentSell))
And here HTML/JS:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<div class="container" style="position: relative; height: 40vh; width: 80vw">
<canvas style="width: 25%" id="myChart"></canvas>
</div>
<input
type="button"
value="add data"
style="margin-top: 25%"
onclick="addData()"
/>
<h1 style="padding-top: 25%">{{product}}</h1>
{% for sell in price %}
<p id="sellprice">{{ sell }}</p>
{% endfor %}
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
<script>
var sellprice = JSON.parse("{{ currentSell | tojson | safe }}");
var product = "{{ product }}";
let myChart = document.getElementById("myChart").getContext("2d");
let priceChart = new Chart(myChart, {
type: "line", // bar, horizontalBar, pie, line, doughnut, radar, polarArea
data: {
labels: [],
datasets: [
{
label: "Sell Price",
},
],
},
options: {},
});
var getData = function () {
$.ajax({
url: "/graph_update/" + product,
success: function (data) {
// process your data to pull out what you plan to use to update the chart
// e.g. new label and a new data point
// add new label and data point to chart's underlying data structures
var sellprice = JSON.parse("{{ currentSell | tojson | safe }}");
priceChart.data.labels.push(sellprice);
priceChart.data.datasets[0].data.push(sellprice);
// re-render the chart
priceChart.update();
},
});
};
// get new data every 3 seconds
setInterval(getData, 10000);
</script>
Thanks!
The issue is that your python code at the endpoint /graph_update/<product> should return data as JSON and currently it is doing the following:
return jsonify('', render_template('graph_update.html', currentSell=currentSell))
You need to return something like
return jsonify(data) # or subset of data that you need to pass
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.
I have a python file that gets the data from database and returns them in the form of JSON.
import pymysql;
import json;
from flask import Flask, render_template, request, redirect, Response
app = Flask(__name__)
#app.route('/test', methods=["POST", "GET"])
def getMySQlData():
tableData = []
connection = pymysql.connect(host='db-auto-performancetesting',
user='DBUser',
password='*******',
database='DbPerformanceTesting',
port=3302,
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
sql = "SELECT TestcaseName, AverageExecutionTimeInSeconds FROM PASPerformanceData WHERE BuildVersion='38.1a141'"
cursor.execute(sql)
while True:
row = cursor.fetchone()
if row == None:
break
tableData.append(row)
tableDataInJson = json.dumps(tableData, indent=2)
print tableDataInJson
return tableDataInJson
finally:
connection.close()
if __name__ == "__main__":
app.run()
I need help in collecting this JSON data into HTML & Javascript and use them as the chart data.
I am new to Javascript and ajax. Can someone help me in writing ajax call to python file from Javascript and retrieve the JSON data returned.
<!DOCTYPE HTML>
<html style="height:100%;">
<head>
<style type="text/css">
body {
overflow:hidden;
}
</style>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript">
window.onload = function () {
var chart1 = new CanvasJS.Chart("chartContainer1", {
title:{
text: "Launch Application"
},
axisY:{
title: "Average Execution Time(seconds)"
},
axisX:{
title: "Software Version",
labelAngle: 180
},
data: [
{
// Change type to "doughnut", "line", "splineArea", etc.
indexLabelFontSize: 16,
labelFontSize: 16,
type: "column",
dataPoints: [
{ label: "ReleaseVersion \n (20.1a121)", y: "**Data recieved from JSON, indexLabel**": "6.0 s" },
{ label: "PreviousVersion \n (38.1a140)", y: "**Data recieved from JSON**", indexLabel: "5.0 s" },
{ label: "CurrentVersion \n (38.1a.141)", y: "**Data recieved from JSON**", indexLabel: "5.4 s" }
]
}
]
});
Thanks
So let me give you quick overview of how might AJAX and flask work together.
Lets say you have some data that you get from database which is something like this
items=[{"id":123,"name":"abc","lastname":"xyz"}]
And you could store something like this with a small piece of code which would be something like this
result = cursor.fetchall()
links = []
num = 0
for item in result:
if links.__len__()-1 != num:
links.append({})
links[num]['id'] = item[0]
links[num]['name'] = item[1]
links[num]['lastname'] = item[2]
#links.append({}) extra append should be created
num += 1
Now the interesting AJAX part
Lets say you have a simple form that you would want to submit.
<form id="searchForm" action="/" method="POST">
<input type="text" id="search" name="search" placeholder="Search">
<input type="submit" value="Search">
</form>
To stop default action for submit you can have a script which would be something like this
$(document).ready(function() {
//#addLinkForm is nothing but the id of the form (works well if you have multiple forms in your page)
$('#addLinkForm').on('submit',function(event){
//This is where the data is sent
$.ajax({
url: '/adminAJAX',
type: 'POST',
data: $('#addLink'),
})
//this is done when the response is received
.done(function(data) {
console.log("success " + data);
});
event.preventDefault();
});
});
The response would be in your browser console. The data received can be used as you see fit
For this to work you would also need
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
in your HTML code
One last thing. For all of this to work you would also need your server side which i guess would be flask for you
#app.route('/adminAJAX',methods=['POST'])
def adminAJAX():
#your processing logic
items=[{"id":123,"name":"abc","lastname":"xyz"}] #just an example
return json.dumps(items)
I am new to django.
From my findings, I tried this way, but didn't work.
<script type="text/javascript" >
var data = {{json}}
</script>
I am trying to use data table from this website, http://www.datatables.net/manual/data.
<script type="text/javascript" class="init">
var temp = '{{campaignList|escapejs}}'; // should be a list, but becomes a string
alert(typeof temp)
$(document).ready( function () {
$('#campaigns').DataTable({
data: temp,
columns: [
{ data: 'id' },
{ data: 'name' },
{ data: 'date' },
]
});
} );
</script>
When I check the type before passing into datatable, the type becomes string.
I also tried {{campaignList|escapejs}} without quote, but didn't work.
Any suggestion? Thanks.
If campaignList is a json string, pass it to safe filter to prevent escape:
var data = {{ campaignList|safe }};
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.