简体   繁体   中英

400 Bad Request Flask

First of all, I've searched this error, tried everything those guys said but it won't work for me.

So, basically, I'm having a login form, and I can't even access the page as it gives me the 400 Bad Request error.

My flask code:

@app.route('/', methods=['POST', 'GET'])
def login():
    users = mongo.db.users
    login_user = users.find_one({'name' : request.form['username']})

    if login_user:
        if bcrypt.hashpw(request.form['pass'].encode('utf-8'), login_user['password'].encode('utf-8')) == login_user['password'].encode('utf-8'):
            session['username'] = request.form['username']
            return redirect(url_for('index'))

    return 'Invalid username/password combination'

My HTML form:

<div class="container">
<div class="row">
    <div class="col-md-4 col-md-offset-4">
        <form method=POST action="{{ url_for('login') }}" enctype="multipart/form-data">
            <div class="form-group">
                <label for="exampleInputEmail1">Username</label>
                <input type="text" class="form-control" name="username" placeholder="Username">
            </div>
            <div class="form-group">
                <label for="exampleInputPassword1">Password</label>
                <input type="password" class="form-control" name="pass" placeholder="Password">
            </div>
            <button type="submit" class="btn btn-primary btn-block">Log In</button>
        </form>
        <br>
    </div>
</div>


I have a similar register page but that works fine, it adds the user to the DB.

I have fixed it. I had to include if request.method == 'POST' under the login index. No idea how I didn't come to this earlier, it makes sense that I was requesting something from the form when I didn't even had the chance to type.

Thanks everyone.

Your html form should be render by login view because in your login view you are trying to get form value:

@app.route('/', methods=['POST', 'GET'])
def login():
    ...
    return render_template('your_htmlform.html')

And now in your form action you can add action={{url_for('index')}} if form submitted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM