How to solve ImportError: cannot import name 'LoginManager' from 'flask_login' in Flask?

Viewed 1631

I am trying a tutorial from https://www.digitalocean.com/community/tutorials/how-to-add-authentication-to-your-app-with-flask-login.

...
from flask_login import LoginManager

def create_app():
    ...
    db.init_app(app)

    login_manager = LoginManager()
    login_manager.login_view = 'auth.login'
    login_manager.init_app(app)

    from .models import User

    @login_manager.user_loader
    def load_user(user_id):
        # since the user_id is just the primary key of our user table, use it in the query for the user
        return User.query.get(int(user_id))   

However, when I am trying to do from flask_login import LoginManager I received the error ImportError: cannot import name 'LoginManager' from 'flask_login'

Edit: I have installed flask_login through pip3 both inside and outside of my virtual environment. However, I am unable to use anything from flask_login. I have tried 'from flask_login import UserMixin' as well and a similar error is produced. I have also checked if flask_login is being installed by doing 'pip3 list' and Flask-Login is found in this list too.

May I ask how can I solve this problem? Thank you in advance!

Solved: I made a stupid mistake of not realizing the error is pointing to files in another directory.

2 Answers

It seems that either you haven't installed flask-login if that is the case then install flask-login by pip install flask-login.

If you have installed, then do confirm that you have activated your virtual environment.

I had this exact error, got solved by:

1:

from flask_login.login_manager import LoginManager
  1. Then I reactivated the virtual env:
deactivate && source venv/bin/activate
Related