Retrieve input value from form in html and use it in flask

12,349

This seems to be working for me. I can access the form data via request.form that functions like a dictionary. You can iterate over the form key, values with request.form.items() (assuming it's python3).

app.py

from flask import Flask, request

app = Flask(__name__)

@app.route("/post_field", methods=["GET", "POST"])
def need_input():
    for key, value in request.form.items():
        print("key: {0}, value: {1}".format(key, value))

@app.route("/form", methods=["GET"])
def get_form():
    return render_template('index.html')

templates/index.html

<html>
<head>
</head>
<body>
  <form action="/post_field" method="post">
    <input type="hidden" name="this_name" value="value1" />
    <input type="submit" value="Press Me!"/>
    </form>
</body>
</html>
Share:
12,349
nyc_arts
Author by

nyc_arts

Updated on June 04, 2022

Comments

  • nyc_arts
    nyc_arts almost 2 years

    So, I need to grab an input value from an html form and use it in flask. Here's an example of python and html for reference:

    python:

    @app.route("/post_field", methods=["GET", "POST"])
    
    def need_input():
    
        for key in request.form["post_field"]:    
    
            if key == "value1":
                #do the thing I want#
    

    html:

    <form action="/post_field" method="post">
        <input type="hidden" name="this_name" value="value1" />
        <input type="submit" value="Press Me!"/>
    </form> 
    

    I get a 400 error when I click that Press Me input.

    • Kyle
      Kyle over 6 years
      What port is your development server running on?
    • nyc_arts
      nyc_arts over 6 years
      @Kyle, localhost:5000
  • nyc_arts
    nyc_arts over 6 years
    perfect! I had thought there was a dictionary involved in there somewhere but didn't know about form.items() with which to grab them. Thank you!
  • Kyle
    Kyle over 6 years
    No problem at all! Glad we could get it figured out.