Search code examples
pythonpython-3.xdictionaryflaskkey

(BadRequestKeyError) Don't know where the problem is


Im trying to make a sign up page and on the page there are two password fields, one for the password itself and the second to confirm the password (and of course a username):

HTML:

<div class="fields">
    <input id="usr" type="text" name="username" placeholder="Username" required>
    <input id="pass" type="password" name="password" placeholder="Password" required>
    <input id="confirmpass" type="password" name="confirm_password" placeholder="Confirm password" required>
</div>

I know what the error is and means, it's a KeyError meaning that it can't find the key i've passed into requests.form, most cases of these errors are misspellings so I checked the spelling multiple times and even copy and pasted the same string.

My problem is that I don't know why the third field^ isn't in requests.form, maybe it's because I have two password types? But I haven't seen anything anywhere saying that it's not allowed.

Error:

File ...
if request.form["confirm_password"]==request.form["password"]
File ...
raise exceptions.BadRequestKeyError(key)
werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.

The error gets raised before the webpage even loads up by the way, not when I submit the form.

Python:

# Accounts = JSON File
@app.route("/signup",methods=["GET","POST"])
def signup():
    if request.method=="GET":
        if request.form["confirm_password"]==request.form["password"]: # Where the error traces back to
            if request.form["username"]not in Accounts.keys():
                Accounts[request.form["username"]]=Accounts["Default"]
                Accounts[request.form["username"]]["Password"]=request.form["password"]
                redirect(url_for("login",name=request.form["username"]))
            else:return render_template(Signup,valid="Username already taken",name=request.form["username"])
        else:return render_template(Signup,valid="Password confirmation does not match password",name=request.form["username"])
    else:return render_template(Signup)

My login page works perfectly it's just this.


Solution

  • The way you've set up your route indicates that you're expecting to receive a POST request. So your code is currently incorrectly expecting a GET request.

    The quick fix is to change the first line of the route to:

    def signup():
        if request.method == "POST":
            # ...