Reputation: 51917
I am designing a page that will have multiple repeated entries. For example:
<input type="text" name="fname1" /><input type="text" name="lname1" />
<input type="text" name="fname2" /><input type="text" name="lname2" />
<input type="text" name="fname3" /><input type="text" name="lname3" />
.
.
.
<input type="text" name="fnameN-1" /><input type="text" name="lnameN-1" />
<input type="text" name="fnameN" /><input type="text" name="lnameN" />
I'm using Flask+Jinja2, so obviously I'm generating that html a la:
{% for fname, lname in names %}
<input type="text" name="fname{{ loop.index }}" value="{{ fname }}" /><input type="text" name="lname{{ loop.index }}" value="{{ lname }}" />
{% endfor %}
But now I want to pull the values out of this form after someone has updated them.
What is the best way to do this? My initial thought was to just do something like this:
for x in range(1, N):
fname = request.form.get("fname%d" % x)
lname = request.form.get("lname%d" % x)
But for some reason that feels clunky to me. I would expect to have something like:
for fname, lname in request.form.get_all('fname%d', 'lname%d'):
# Stuff here
And of course I haven't found anything in my searches or I'd be posting the answer here as well. Is there a "best way" to do this, or should I just roll my own?
Upvotes: 4
Views: 2503
Reputation: 33349
Here is the solution that was discussed in comments. I answered it earlier
Dynamic form fields in flask.request.form
Upvotes: 2