How do I have a login form with multiple post and get requests in flask


How do I have a login form with multiple post and get requests in flask. Basically, I have a login page, first I would like to check whether the username is taken yet, then post the password part of the form. This all should happen in the same page.


You can create two ajax request, one for the username check another one for login. Or one ajax and one form post.

<!-- login.html -->

<script src=""></script>

<form method="POST">
    <label for="username">Username</label>
    <input type="text" name="username" id="username"><br>
    <p id="username-text"></p>
    <label for="username">Password</label>
    <input type="text" name="username" id="username"><br>
    <input type="submit" name="submit">

    $('#username').keyup(function() {
        data = {'username': $('#username').val()}
        $.post("{{ url_for('check_username') }}", data, function(data, status){

If you want to redirect your page after login, then just post the data as it is. If you don’t want to redirect, write one more ajax for authentication.

@app.route('/login', methods=["GET", "POST"])
def login():
    if request.method == 'POST':
        # validate you creds ....
        # redirect() if needed
    return render_template('login.html')

@app.route('/check_username', methods=["POST"])
def check_username():
    username = request.form['username']
    # write the query for username check
    found = ''
    if found:
        return {'msg': 'Username taken'}
        return {'msg': 'Username is available'}

Answered By – NavaneethaKrishnan

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published