Post values from an HTML form and access them in a Flask view

前端 未结 2 1420
北荒
北荒 2020-11-22 15:34

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

相关标签:
2条回答
  • 2020-11-22 16:00

    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 }}">
    
    0 讨论(0)
  • 2020-11-22 16:17

    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')
    
    0 讨论(0)
提交回复
热议问题