Zion
Zion

Reputation: 1610

Get value of a form input by ID python/flask

How do you get the actual value of the input id after you send it in Flask?

form:

<form  action="" method="post">
    <input id = "number_one" type="text" name="comment">
    <input type="submit" value = "comment">
</form>

like, what I am trying to say is when the form is sent (i.e. when you do this):

request.form.get("comment")

the value of the text field is passed. What I can't figure out is how to get the value of the id.

So, when the form is sent we could then tell from which form the info was coming from, because each form has a unique id. In this case the id is number_one.

So, how do we go about getting the actual literal value of the id and not the text input?

Upvotes: 10

Views: 35534

Answers (2)

Bharti Rawat
Bharti Rawat

Reputation: 2063

There is a one way to identify the fields and also multiple forms together....

use this

<input value = "1" type="hidden" name="my_id">

so at your view file you can retrieve this value.

my_id = request.form.get("my_id","")
print my_id

your output will be

1

you can also do this...

my_id = request.form.get("my_id","")
if my_id == "1":

    ** for example **

    value = request.form.get("any_parameter_of_form","")

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121904

You can't. The id value is not part of the form data set sent by the browser.

If you need to identify the field, you'll have to either add the id to the input element name, or if the id is generated by Javascript code, perhaps store the information in an extra hidden field.

Adding the id to the name could be done with a delimiter perhaps:

<input id = "number_one" type="text" name="comment.number_one">

which would require you to loop over all form keys:

for key is request.form:
    if key.startswith('comment.'):
        id_ = key.partition('.')[-1]
        value = request.form[key]

Upvotes: 14

Related Questions