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

Issue

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.

Solution

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="https://code.jquery.com/jquery-3.5.1.min.js"></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">
</form>

<script>
    $('#username').keyup(function() {
        console.log(";ok")
        data = {'username': $('#username').val()}
        $.post("{{ url_for('check_username') }}", data, function(data, status){
            $('#username-text').text(data['msg']);
          });
    })
</script>

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 ....
        authenticate(request.POST)
        # 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'}
    else:
        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