younus
younus

Reputation: 474

werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand. KeyError: 'id'

html page

{%block title%}Login page{% endblock %}

{%block content%}
<form action = '#' method="post">
   <p>creds:</p>
   <p><input type="number"  placeholder="id"  Id="id" /></p>
   <p><input type="text"  placeholder="nm"  name="nm" /></p>
   <p><input type="submit" value="submit" /></p>
</form>
{%endblock%}

app code

@app.route("/")
def home():
    return render_template("login.html")

@app.route("/",methods = ["POST","GET"])
def post():
    if request.method == "POST":
        user = request.form['nm']
        id = request.form['id']
        sql = ('''INSERT INTO abc
                (id, name) VALUES (?, ?)
                ''')
        val = (id,user)
        cur.execute (sql, val)
    return 'Ok'

I tried using return.form.get('id'), but its returning null.

Can anyone please help me on this?

Upvotes: 10

Views: 60337

Answers (3)

Omar
Omar

Reputation: 61

I had exactly the same problem, but mine was with a "SelectField" , the update fields would be "None" and to avoid that I just added option value None as shown below:

<option value="None">None</option>

This fixed my problem

Upvotes: 2

Subham Sarkar
Subham Sarkar

Reputation: 59

When you use request.form["something"] you assume that this something always be part of your request, I recommend you to use request.form.get("something", False) to avoid that error. I hope this will solve your doubts.

Upvotes: 6

Swapnil Suryawanshi
Swapnil Suryawanshi

Reputation: 354

<p><input type="number"  placeholder="id"  name="id" /></p>

you have typed Id instead of name

Upvotes: 13

Related Questions