[FIXED] Flask forms – Handle multiple identical form fields

Issue

I have the following code to display information in a shopping-cart manner:

<form method="POST" action="/updateorder/{{item.idordre}}">
  {%for parts in viewParts %}   
    <div class="invisible"> 
    <input class="form-control" id="idpart" name="idpart" value="{{parts.idpart}}"></div>           
    <td><div class="form-group col-md-3">
    <input class="form-control" id="quantity" name="quantity" required type="number" value="{{parts.quantity}}">
    </div></td>       
  {%endfor%}
 <div class="container"> 
    <input class="btn btn-warning btn-md" id="submit" name="submit" type="submit"value="Update quantity">
   </div>
   </form>

There might be several instances of the same formfields with idpart and quantity where the user can change the quantity and submit the update.

@app.route('/updateorder/<int:ident>',methods=['GET','POST'])
def updateorder(ident):
form = updateOrder()
if request.method =="POST":
    quantityChange = request.form.to_dict()
    dostuff()

When i receive the form in my route i only get the first form value.
Is it possible to receive data like this at all?

Solution

If you’re saying you have multiple fields with same name in the same form, then submitting the form will only give you one instance of it (because they have the same names, they overwrite each other or you will get just the instance that has a value)

A possible solution is to make the names unique by appending an index to the name e.g. idpart_1, idpart_2 (you can even use the idpart number itself i.e. idpart_{{idpart}}. On submit, you then process the names via a pattern e.g.

for k,v in request.form.items():
    if k.startswith("idpart_"):
        # This field is an idpart number. You can then figure out which one it is
        idpart = k.split("idpart_")[1] # Tells you which one you're dealing with

Answered By – NoCommandLine

Answer Checked By – Katrina (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published