Search code examples
pythonflaskjinja2

Flask Redirect From Jinja HTML Template


I can call the redirect method from .py file like this

@app.route('/logout', methods=['POST', 'GET'])
def logout_page():
    logout_user()
    flash('Anda telah logout', category='success')
    return redirect(url_for('login_page'))

How to call that redirect method from the Jinja HTML template?

I've tried something like this

{% if not current_user.is_authenticated %} 
  {% redirect(url_for('login_page')) %}
{% else
...
%}

But it's not works


Solution

  • If you use the login_required decorator, it will ensure that the user is logged in before calling the endpoint. Thus, the template is not rendered at all. The user can be directed to login.

    from flask_login import login_required
    
    # ...
    
    @app.route('/')
    @login_required
    def secret_endpoint():
        return 'This is secret.'
    

    In order to implement such a forwarding to the login, the attribute login_view must be set for the LoginManager. Here it is determined where the user is directed if he is not logged in.
    If this attribute is not set, only the HTTP error 401 is returned.

    from flask_login import LoginManager
    
    # ...
    
    login_manager = LoginManager()
    login_manager.login_view = 'login_page'
    login_manager.init_app(app)
    
    # ...
    

    You can find an explanation of the behavior in the documentation here.