In the past, I have used flask forms to take a piece of info from a form and redirect to the correct page, based on this form input, e.g.:
def index():
form = utils.IndexForm()
choices_lst = form.choices_lst
choice=form.type_of_testing.data
if form.validate_on_submit():
print("choice: ",form.type_of_testing.data)
if form.type_of_testing.data in choices_lst:
print('Going to type1 form')
return redirect(url_for("type1",choice=choice))
else:
print('Going to type2 form')
return redirect(url_for("type2",choice=choice))
else:
print("Validation Failed")
print(form.errors)
return render_template('index.html',form=form)
I now want to change this logic and remove the form and instead just have 3 buttons to chose from, and go to the correct page based on which button is clicked, and pass along the correct ID associated with the button.
My route.py
page current likes like this:
@app.route('/choices/',methods=['GET'])
def choices():
choice_list = [1,2,3]
return render_template('choices.html',choice_lst=choice_lst)
@app.route('/choice_info/')
def event_info():
#some logic based off of the choice data passed along
return render_template('choice_info.html')
The HTML for the choices.html
page looks like this:
{% extends "base.html" %}
{%block title%}Networking{%endblock%}
{%block main_content%}
<div >
<div >
<table >
<tbody>
{% for choice in choice_lst %}
<tr>
<td><a href="/{{ choice['name'] }}"><img src={{ choice["imageURL"] }}> </a></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{%endblock%}
I thought that passing the choice[name]
as a parameter to the URL would work, but I am getting a 404 not found error. I can't quite figure out how to pass the correct choice along in my HHTML, and Im not sure what functions I need in my route.py
code to make the logic work either.
CodePudding user response:
from flask import url_for
@app.route('/choices/',methods=['GET'])
def choices():
choice_list = [
{'name': url_for('event_info', choice_id=1)},
{'name': url_for('event_info', choice_id=2)},
{'name': url_for('event_info', choice_id=3)}]
return render_template('choices.html',choice_lst=choice_lst)
@app.route('/choice_info/<choice_id>')
def event_info(choice_id: int):
#some logic based off of the choice data passed along
return render_template('choice_info.html')
Also, remove the /
from "/{{ choice['name'] }}"
in this line in your HTML:
<a href="/{{ choice['name'] }}"><img src={{ choice["imageURL"] }}> </a>