Reputation: 5526
I am trying to find how I can pass a URL parameter (not request) into the url_for
function, but I cant find it. In the following example, I need to pass the q_id
through the form, as I do with incrRight
. So, how can I have variables in url_for
in this scenario ?
<form action="{{url_for('answer',q_id='5495eb77433f064294361ceb')}}" method="post">
<input type="text" name="incrRight" value="0">
<input type="submit"/>
</form>
This is what I have on my controller:
@app.route('/api/v1.0/question/<string:q_id>/answer', methods = ['POST'])
def answer(q_id):
incrRight = request.form.get('incrRight')
. . .
I need my html form to be able to communicate with the above function, by passing a q_id and the incrRight parameter.
Upvotes: 1
Views: 4475
Reputation: 1122282
You can add additional form parameters by adding more <input>
tags. If the user of the form is not supposed to changed the items, use a <input type="hidden">
element:
<form action="{{ url_for('answer') }}" method="post">
<input type="text" name="incrRight" value="0" />
<input type="hidden" name="q_id" value="5495eb77433f064294361ceb" />
<input type="submit"/>
</form>
This does require that the answer()
view can be invoked without the q_id
parameter, of course:
@app.route('/api/v1.0/question/answer', methods=['POST'])
@app.route('/api/v1.0/question/<string:q_id>/answer', methods = ['POST'])
def answer(q_id=None):
if q_id is None:
q_id = request.form['q_id']
incrRight = request.form.get('incrRight')
Here a missing q_id
parameter in the URL signals to the view that the browser included the question id in the POST body instead.
Another option is for you to write JavaScript code that'll adjust the form action
parameter based on the q_id
field in the form, but this then requires that your visitors have JavaScript enabled.
Upvotes: 2