I am trying to pass the jinja variable generated within for loop to backend when corresponding button is clicked. When i click any button the first value in the list is passed. The code I tried is
Code
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/search_tag', methods=["GET", "POST"])
def search_tag():
if request.method == 'POST':
print("hi")
tag_x = request.form['rawtext']
print(tag_x)
return render_template('index.html', messg = "SUCCESS")
else:
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
Html Code
<!DOCTYPE html>
<html>
<head>
<title>Test App</title>
</head>
<body>
<form method="POST" action="{{ url_for('search_tag')}}">
<div id ="result">
<p style="color:red">
{% for i in ["hello","hi","travel","goal"] %}
<li>{{ i }}
<input type="hidden" id="rawtext" name="rawtext" value="{{ i }}">
<input type="submit" name="submit" value="click" >
</li>
{% endfor %}
</p><br>
</div>
</form>
{{ messg }}
</body>
</html>
</body>
</html>
Thanks in advance
CodePudding user response:
Change {{i}}
with {{loop.index}}
. When you have a loop in jinja you cant pass the i variable inside the for loop.
CodePudding user response:
I solved by using radio button and advice from @Ioannis Skaltsas (Thanks for you suggestion. If there is any better way please suggest like ajax or something else).. Corrected code is --->
<!DOCTYPE html>
<html>
<head>
<title>Test App</title>
</head>
<body>
<form method="POST" action="{{ url_for('search_tag')}}">
<div id ="result">
<p style="color:red">
{% for i in ["hello","hi","travel","goal"] %}
<input type="radio" id="rawtext" name="rawtext" value="{{ loop.index }}">{{ i }} <br>
{% endfor %}
<input type="submit" name="submit" value="click" >
</p><br>
</div>
</form>
{{ messg }}
</body>
</html>
</body>
</html>
Since originally list was generated in the python code(here statically used in html code), based on the selected loop index submitted using button, I could take the value from list at the python end.