Flask how to redirect to previous page after successful login

16,150

Solution 1

There may be several problems:

  • url_for skips query param if it has None value
  • your login endpoint takes POST requests. In such case you have to get the next param such way request.form.get('next')

If these tips do not help you, you can put import ipdb;ipdb.set_trace() (may be you have to install ipdb first) in your code and try to debug it for better understanding what is going on here or put more context for understanding your problem.

Solution 2

Use session to keep track of the previous url, for example:

@app.route('/profile')
def profile():
    if user_not_logged_in:
        session['url'] = url_for('profile')
        return redirect(url_for('login'))
    return rendertemplate('profile.html')

@app.route('/login')
def login():
    if login == True: #assuming login was successful
         if 'url' in session:
            return redirect(session['url'])
         return redirect(url_for('anyother_url'))
Share:
16,150

Related videos on Youtube

jas
Author by

jas

Updated on September 14, 2022

Comments

  • jas
    jas over 1 year

    I have a webapp where I don't use Flask-login. If user visit a link and is not logged in, I redirect the user to login page. I achieve this my setting 'username' in session and checking that when user tries to access some link directly without logging in i.e in that case username will be null.

    I have tried to follow this SO solution, but the next parameter is always None. I have tried both solution but can't get either one to work.

    username = session.get('username')
    if username:
        # go to home 
    else:
        next_url = request.url
        login_url = '%s?next=%s' % (url_for('login'), next_url)
        return redirect(login_url)
    

    Second solution

    username = session.get('username')
    if username:
        # go to home 
    else:
        return redirect(url_for('login', next= request.url))
    

    print (request.url) = localhost:5000/visitPage

    Login Function

       if 'next' in request.args:
         return redirect(next)
       else:
         return redirect(url_for("user.index"))
    

    Here when I print (next), it is None
    But login url has next argument

    http://localhost:5000/login?next=http%3A%2F%2Flocalhost%3A5000%2FvisitPage

  • jas
    jas about 7 years
    Issue was in Login function. Login func does form validation and redirected the user if form data is invalid. So, in this case first call to login function resulted in re-direct and the next data was gone on second request. Had to save the next data between the two request and everything worked fine.