8

I have an HTML form that gets posted to a Flask route. However, request.form is empty. If I try to access one of the values by id, I get a 400 error. How do I post values from an HTML form and access them in Flask?

<form method="POST">
  <input id="my_input" type="text" value="{{ email }}">
  <input id="my_submit" type="submit" value="Submit">
</form>
@app.route('/page', methods=['POST', 'GET'])
def get_page():
    if request.method == 'POST':
        print(request.form)  # prints ImmutableMultiDict([])
        print(request.form['my_input'])  # raises 400 error
    return render_template('page.html')
davidism
  • 121,510
  • 29
  • 395
  • 339

2 Answers2

12

Your input doesn't have a name attribute. That is what the client will pass along to the server. Flask will raise a 400 error if you access a form key that wasn't submitted.

<input name="my_input" id="my_input" type="text" value="{{ email }}">
davidism
  • 121,510
  • 29
  • 395
  • 339
dirn
  • 19,454
  • 5
  • 69
  • 74
-2

You need to Specify the form Action method in the Html page, and then mention the HTML Text box name inside the Tag.

<form method="POST" action="/PythonFunctionName">
  <input id="my_input" type="text" name="HTMLControlName" value="{{ email }}">
  <input id="my_submit" type="submit" value="Submit">
</form>

And inside the .py module access the element using the name specified in the HTML tag.

@app.route('/PythonFunctionName', methods=['POST', 'GET'])
def getPage():
    if request.method == 'POST':
        strTextBoxVal= request.form['HTMLControlName'])
        Print(strTextBoxVal) 
    return render_template('page.html')
Chikku Jacob
  • 2,114
  • 1
  • 18
  • 33