0

I have a form which is like

<form action="{{ url_for('my_form')}}" method="get">

            <h2><td><input type="hidden" name="user_name" value="{{ user_name }}">{{ user_name }}</td></h2><br>

             <button type="submit" class="btn btn-primary btn-lg" value="Submit">Submit</button>
          </form>

And then on flask backend

@app.route('/my_form', methods=['GET'])
def my_form():
    print request.form.items()
    user_name = request.form['user_name']
    print "exclusive request"
    print "got user name ", user_name

But this doesnt work as the submit query becomes http://local_host/my_form?user_name=foobar <--- 400 error

which makes sense.. as the query url is my_form So, the question is how to make a get form in flask?

frazman
  • 29,933
  • 66
  • 171
  • 257

2 Answers2

1

According to the flask documentation we use form attribute of request only with POST method or PUT in your case as you are using GET try args parameters:

form A MultiDict with the parsed form data from POST or PUT requests. Please keep in mind that file uploads will not end up here, but instead in the files attribute.

args A MultiDict with the parsed contents of the query string. (The part in the URL after the question mark).

use this in your backend :

@app.route('/my_form', methods=['GET'])
def my_form():
    print request.args.items()
    user_name = request.args['user_name']
    print "exclusive request"
    print "got user name ", user_name
Espoir Murhabazi
  • 5,134
  • 2
  • 40
  • 66
1

You are try to access to POST request parameter but your route accept only GET request. To resolve this just add POST in the method argument of your route decorator.

@app.route('/my_form', methods=['GET', 'POST'])
def my_form():
    print request.args.items()
    user_name = request.form.get('user_name')
    print "exclusive request"
    print "got user name ", user_name
Ignacio Vergara Kausel
  • 4,786
  • 3
  • 34
  • 40
Noxiz
  • 249
  • 1
  • 8