How to get the Jinja2 generated input value data?
Solution 1
Forms get confused when you use the same name for each input name. You could either create a separate form around each table cell with the first name or you can use the jinja2 loop index to create unique input names...
<input id="firstname{{ loop.index }}" name="firstname{{ loop.index }}" type="text" value='{{ user.FirstName }}' />
Hope this helps!
Solution 2
request.form
is a werkzeug.datastructures.MultiDict
. You can get out all the values for a field with its getlist
method:
a_firstname = request.form['firstname']
all_firstnames = request.form.getlist('firstname')
If you need the names to be in the order they were defined in the form you need to subclass flask.Request
and set its parameter_storage_class
to an instance of ImmutableOrderedMultiDict
. Then you need to set the request_class
field on your Flask
instance:
from flask import Flask, Request
from werkzeug.datastructures import ImmutableOrderedMultiDict
class OrderedRequest(Request):
parameter_storage_class = ImmutableOrderedMultiDict
app = Flask(__name__)
app.request_class = OrderedRequest
Then request.form.getlist('firstname')
will return the fields in the order the browser sent them (which is conventionally in the order they are defined in the HTML).
Tianyun Ling
Updated on June 12, 2022Comments
-
Tianyun Ling almost 2 years
In my HTML file, I have:
<table> {% for user in user_data_html %} <tr> <td> <input id="firstname" name="firstname" type="text" value='{{ user.FirstName }}' /> </td> <td> <input name="submit" type="submit" value='update' /> </td> </tr> {% else %} <tr><td>no user found</td></tr> {% endfor %} </table>
I want to modify the user name in the webpage by clicking update button in each row. But I always get the first "firstname" using the following python code in the backend:
firstname = request.form['firstname']
How can I solve this problem?