Reputation: 652
I have a dynamically generated number of rows containing text boxes in a table with a default value (order_quantity). Basically on a post I want my items table in sql to be updated with the values of these text boxes according to their ID's.
{% for i in items %}
<tr>
<td>
...
</td>
<td>
...
</td>
<td>
<div class="form-group">
<input type="number" id="amount" name="amount" value="{{ i.order_quantity }}">
</div>
</td>
<td>
...
</td>
</tr>
{% endfor %}
There's no problem passing in the order_quantity OR the item ID but not both obviously.
HTML:
<input type="number" id="amount" name="amount" value="{{i.item_id}} {{ i.order_quantity }}">
Python:
amount = request.form.getlist('amount')
print amount
for i in amount:
print i
In summary, how can I pass both the quantity and its relative id out in a simplistic manner for easy server-side extraction for each text box?
Upvotes: 3
Views: 13484
Reputation: 652
An adapted solution of junnytony's worked for me-
amounts = request.form.getlist('amount')
item_ids = request.form.getlist('item_id')
for idx, am in zip(item_ids, amounts):
print idx, am
Using the hidden input field (item_id) as suggested above.
Upvotes: 0
Reputation: 808
So there's a few hacky ways you can do this, you could for example comma delimit the ID and amount in the value eg,
<input type="number" id="amount" name="amount" value="{{ i.order_quantity }}_{{ i.item_id }}">
and then split it on the server side with some logic.
for item in request.args:
quantity, item_id = item.split('_')
But the above assumes you're not going to be editing the amount in the form. Which will probably be useless in most scenarios. So let's look at a more editable solution...
I'd personally do it this way, by putting the item ID in the name
<input type="number" id="amount" name="amount-{{ i.item_id }}" value="{{ i.order_quantity }}">
And then use the logic
for key, amount in request.args.items():
item_id = key.split('-')[1]
# And the amount var has the amount.
Upvotes: 1
Reputation: 3535
I think you can achieve what you want by adding a hidden input field that holds the item_id
Example:
<td>
<div class="form-group">
<input type="number" id="amount" name="amount" value="{{ i.order_quantity }}">
<input type="hidden" name="item_id" value="{{ i.item_id }}"/>
</div>
</td>
When you receive the input in Flask, you can match the id's to the amounts since the order is preserved.
amounts = request.form.getlist('amount')
item_ids = request.form.getlist('item_id')
for item_id, idx in enumerate(item_id):
amount = amounts[idx]
# do something with item_id and amount
Upvotes: 8