I have a dynamic dropbox using jinja loop. As part of the condition, I want to use a value from another dropbox. For this, I am setting up a global variable using scenario_id = $('#scenario').val(); in an onchange function for the other combo. It works ok. I also show it on the page.
However, when I use scenario_id as part of the if statement, it does not work. It does not use the correct value. It is potentially null ( I am not sure).
So, the below code does not create a correct select field. If I replace the scenario_id with a static known id, it works okay for that selected scenario.
Can you please help me to be able to use dynamic value here?
Kind Regards,
Sofia
<SELECT name="source1" id="source1">
{% for node in allowed_values_nodes %}
{% if node[0]==edge.source_id and node[2]== scenario_id%}
<OPTION value = {{node[0]}} selected>{{node[1]}}</option>
{% endif %}
{% if node[0]!=edge.source_id and node[2]== scenario_id%}
<OPTION value = {{node[0]}}>{{node[1]}}</option>
{% endif %}
{% endfor %}
</SELECT>
I added the code already.
How to compare javascript variable "var1" with django multiple values. If a answer is ok, program should say ¡very good!
Django + Javascript:
<script>
var var1 = document.getElementById("userAnswer").value;
if (
{% for textEUS in question.textEUS.all %}
var1 == {{ textEUS }}
{% endfor %}
){
alert(¡Very good!);
}
</script>
only Django:
{% for textEUS in question.textEUS.all %}
{{ textEUS }}
{% endfor %}
only Javascript:
<script>
function tocorrect(){
var var1 = document.getElementById("userAnswer").value;
if (var1 == "answer"){
alert(¡Very good!);
}
}
</script>
What you're trying to do isn't possible the way you're trying to do it. This is the order of things:
Django renders a page using the django template language. This page might consist of HTML, javascript, and text really. All of the django tags, filters, variables have been assessed and processed at this point. For example:
{% for textEUS in question.textEUS.all %}
{{ textEUS }}
{% endfor %}
will have turned into a list of text.
The page rendered above is sent to your users browser
In the browser, the page is loaded, and javascript is executed, but at this point there are no more django template-tags etc.
The key point is:
You can't expect django template tags to 'run' at the sametime as your javascript. One happens on the backend, the other on the frontend.
You can however set a javascript variable using the django template language in the backend, and then use it in the front-end:
<script>
var var1 = document.getElementById("userAnswer").value;
// create a variable called textEusAll, this is completed in the backend
// before the page is sent to the user
var textEusAll = [
{% for textEUS in question.textEUS.all %}
"{{ textEUS }}"{% if not forloop.last %},{% endif %}
{% endfor %}
]
// use plain javascript for stuff happening in the front-end
if (textEusAll.includes(var1)) {
alert("¡Very good!");
}
</script>
I have a Python code where I'm using Flask to create a webpage. In the home page, I'm filling out a form, submitting using a button and it displays a table based on the inputs.
The problem i'm having is that once I click the button to submit the form, it renders the table on that same webpage. I would like to create a new window using JavaScript window.open() or whatever other method you might suggest to render that table inside the new window and leave the home page as it is. I tried looking around and I can't seem to get anything to work. I've read through this question and this question. But those suggestions don't seem to match what i'm looking for.
This is my code:
Python code
from flask import Flask, render_template, request,
app = Flask(__name__)
def get_table(user_input):
...
return dict //returns list of dictionaries, for example...
//dict = [{'name':'Joe','age':'25'},
// {'name':'Mike','age':'20'},
// {'name':'Chris','age':'29'}]
#app.route("/")
def home():
return render_template('home.html')
#app.route("/table", methods = ['POST'])
def table():
user_input = request.form['input']
dict_table = get_table(user_input) //return list of dictionaries
return render_template('table.html', dict_table=dict_table)
if __name__ == '__main__':
app.run(debug=True)
home.html
<!DOCTYPE html>
<html>
<head>
<title>Homepage</title>
</head>
<body>
<form action="/table" method="post">
<select name="input">
<option value="1">Input</option>
</select>
<button type="submit">Click Me!</button>
</form>
</body>
</html>
table.html
<!DOCTYPE html>
<html>
<head>
<title>Table</title>
</head>
<body>
<table id="table">
{% if dict_table %}
<tr>
{% for key in dict_table[0] %}
<th>{{ key }}</th>
{% endfor %}
</tr>
{% endif %}
{% for dict in dict_table %}
<tr>
{% for value in dict.values() %}
<td>{{ value }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
</body>
</html>
Could someone explain in a clear way how I can click the form submit button on my homepage, stay on the homepage home.html, and make the table from table.html open up in a new window (maybe using window.open() from JavaScript or something else)?
I would appreciate it if someone could walk me through the steps on how to do this with my code provided and show me specifically where to call functions and things like that. I'm new to Flask/HTML/JS and I'm just trying to learn for personal use and I'm getting frustrated reading links and documents that show just how to display a URL like google.com in a new tab, which is not what I want. Thanks!
Step1: Check out this link that explains how to use Jquery and Ajax with FLASK
The key concept here is AJAX (asynchronous JavaScript and XML). In short, it is an architecture that makes it possible to send requests to the server in the background (called Asynchronous requests) and then modifies the content of the page currently displayed by the web browser according to the result received from the server, avoiding as well as the server does not transmit the complete page again.
Step2: A solution to your problem
First we write the routes:
from flask import Flask, render_template, request,
app = Flask(__name__)
user_input = None
def get_table(user_input):
...
return dict # returns list of dictionaries, for example...
# dict = [{'name':'Joe','age':'25'},
# {'name':'Mike','age':'20'},
# {'name':'Chris','age':'29'}]
#app.route('/')
def home():
return render_template('home.html')
#app.route('/_ajax_user_input')
def ajax_user_input():
global user_input
user_input = request.args.get('user_input', 0, type=int)
return "ok"
#app.route("/table")
def table():
x = user_input
dict_table = get_table(x) # return list of dictionaries
return render_template('table.html', dict_table=dict_table)
After we attack the templates:
home.html:
<select id="input" name="input">
<option value="1">Input</option>
</select>
<button type="button" class="test"> Click Me! </button>
<script>
$(document).ready(function(){
$('.test').bind('click', function() {
$.getJSON($SCRIPT_ROOT + '/_ajax_user_input',{
user_input: $('#input').val(),
},function() {
window.open('http://127.0.0.1:5000/table', '_blank');
});
return false;
});
});
</script>
table.html:
<table id="table">
{% if dict_table %}
<tr>
{% for key in dict_table[0] %}
<th>{{ key }}</th>
{% endfor %}
</tr>
{% endif %}
{% for dict in dict_table %}
<tr>
{% for value in dict.values() %}
<td>{{ value }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
Basically here is what happens:
when I click on my button, I call the Javascript script:
$('.test').bind('click', function() {
This sends an ajax request to FLASK, which consists in executing the ajax_user_input() function:
$.getJSON($SCRIPT_ROOT + '/_ajax_user_input',
To this function I send a data (the value selected by the user in the select tag) and this data is stored in the variable user_input:
user_input: $('#input').val(),
On the side of Flask I get the data and I store it in a global variable that I named user_input too:
global user_input
user_input = request.args.get('user_input', 0, type=int)
Then in my script I call a javascript method that allows me to open a url in a new tab (more details here):
window.open('http://127.0.0.1:5000/table', '_blank');
The 'table' route, stores in the variable x the data previously stored in my global variable (user_input), then it calls the function get_table() (by passing him the variable x in parameter) which returns a list of the dictionaries, and finally it returns the page table.html with the list of the dictionaries in parameter:
x = user_input
dict_table = get_table(x)
return render_template('table.html', dict_table=dict_table)
I hope this will help you, even though I am convinced that there are many other ways to do it, perhaps more effective.
Hi I am building a simple blog using Python/Django. In my index.html file, I am trying to show archived posts when a button containing a month is clicked. At the moment, I am just trying to get the id of every post made in that month into a javascript array. For some reason though,it always returns true!
<script type="text/javascript">
function showPosts(month)
{
var posts_in_month=[];
{% for post in all_posts %}
var match = {{ post.pub_date.month }}
{% ifequal match month %}
posts_in_month.push({{ post.id }})
{% endifequal %}
{% endfor %}
}
</script>
I then go on to have a switch statement where I show the contents of the array depending on the month clicked. The code definitely works, when I call an alert(month) it shows up correctly, and when I call alert({{ post.pub_date.month }}) it shows up fine as well. These are usually not the same though, why is it always evaluating the ifequal to true?
You cannot create Javascript variable in python and use it as python's variable.
Replace the match with actual value:
{% ifequal post.pub_date.month month %}
posts_in_month.push({{ post.id }})
{% endifequal %}
I pass some data and process in my django template file. It works just fine. However, when i right click and then select "view page source" on my internet browser, i can see all the values that i passed from my view.py. How to hide the values in the template file.
Child.page
{% extends "base.html" %}
{% block title %}My amazing blog{% endblock %}
{% block extra_js %}
<script>
var secret_data = new Array();
function mybutton(){
{% for data in Mysecret%}
// Here, I wanna make the value of data invisable
secret_data.push({{ data.0 }})
{% endfor %}
}
</script>
{% endblock %}
{% block content %}
<input type="submit" name="submitButton" value="Submit" onclick ="mybutton();"> </input>
{% endblock %}
When i right click and select "view to source" on my internet browser, i can see all the values something like that:
<script>
var secret_data = new Array();
function mybutton(){
secret_data.push("Secret-1")
secret_data.push("Secret-2")
}
</script>
I have tried this:
secret_data.push({% csrf_token %}{{ data.0 }})
The values cannot be seen in case of viewing source code of the page, but at the same time it messes up the data that i pass (cannot access data cause the data turns out a div). How can i make my secret_data list invisible so that if someone tries to view source of my page, she would not be able to see the passed values ("Secret-1" and "Secret-2").