2

Multiple questions have been asked with a similar error on SO. I have tried all of the solutions but still keep getting a beautiful error:

werkzeug.exceptions.HTTPException.wrap..newcls: 400 Bad Request: KeyError: 'username'

Below is my html form:

<form action='/login' method = "GET">
    <label>Name: </label>
    <input name="username" type="text">
    <input type="submit" name='submit' value='submit'>
</form>

Here is the function that deals with the form data:

@app.route('/login', methods = ['GET'])
def login():
    if request.method == "GET":
        un = request.form['username']
        return un

I have learned Bottle and transitioning towards Flask. So far, I have tried the following: 1) GET to POST 2) request.form.get('username', None) 3) Add POST reason to the function route without any rhyme or reason.

Can somebody help me out?

petezurich
  • 9,280
  • 9
  • 43
  • 57
Ajay Shah
  • 414
  • 5
  • 10

2 Answers2

4

You need to change the method (GET to POST) in the html file and add the method in the decorator @app.route too. Do not forget that in this case a return (GET) is required to render the html file.

@app.route("/login", methods = ['GET', 'POST'])
def login():
if request.method == "POST":
    # import pdb; pdb.set_trace()
    un = request.form.get('username', None)
    return un

return render_template('form.html')

Tip: Learn about pdb to debug your programs more easily.

https://realpython.com/python-debugging-pdb/

https://docs.python.org/3/library/pdb.html

1

no need to change your form action method. but when you use GET method for sending form data your data is transmitted as URL variables and you need to read data this way:

if flask.request.method == 'GET':
    username = flask.request.args.get('username')

and if you change the method to POST, read content as below:

if flask.request.method == 'POST':
    username = flask.request.values.get('username')
Mehdi
  • 278
  • 4
  • 11