Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value of a form input by ID python/flask

Tags:

python

html

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?

like image 662
Zion Avatar asked Aug 15 '15 07:08

Zion


People also ask

How do I get values from form Flask?

You can get form data from Flask's request object with the form attribute: from flask import Flask, request app = Flask(__name__) @app. route('/', methods=['GET', 'POST']) def index(): data = request.

How do I get HTML form data in Python?

To post HTML form data to the server in URL-encoded format using Python, you need to make an HTTP POST request to the server and provide the HTML form data in the body of the Python POST message. You also need to specify the data type using the Content-Type: application/x-www-form-urlencoded request header.


1 Answers

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]
like image 117
Martijn Pieters Avatar answered Sep 21 '22 15:09

Martijn Pieters