Python Flask: AttributeError: 'NoneType' object has no attribute 'is_active'

kramer65 picture kramer65 · Jan 23, 2014 · Viewed 9.1k times · Source

Using the Flask Mega Tutorial I'm trying to learn Flask. In part 5 of the tutorial I'm now building a profile page which needs the user to be logged in.

Since I'm using the peewee ORM instead of SQLAlchemy, I do adjust the code here and there, but for this case I don't think that matters. I now login using my Google (openID) account and hit an error saying AttributeError: 'NoneType' object has no attribute 'is_active'. The error occurs at the end of this function at the line which says login_user(user, remember = remember_me).

@oid.after_login
def after_login(resp):
    if resp.email is None or resp.email == "":
        flash('Invalid login. Please try again.')
        return redirect(url_for('login'))

    user = User.select().where(User.email == resp.email).first()

    if user is None:
        nickname = resp.nickname
        if nickname is None or nickname == "":
            nickname = resp.email.split('@')[0]
        User(nickname = nickname, email = resp.email, role = models.ROLE_USER, last_seen = datetime.utcnow()).save()

    remember_me = False
    if 'remember_me' in session:
        remember_me = session['remember_me']
        session.pop('remember_me', None)
    login_user(user, remember = remember_me)
    return redirect(request.args.get('next') or url_for('index'))

Since this piece of code worked before, I wouldn't know why this now gives an error. The is_active method (not attribute) occurs in the User class, which looks like this:

class User(db.Model):
    nickname = CharField()
    email = CharField(max_length=150)
    role = IntegerField(default = ROLE_USER)
    about_me = TextField(null = True, max_length=140)
    last_seen = DateTimeField()

    def is_authenticated(self):
        return True

    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def get_id(self):
        return self.id

    def avatar(self, size):
        return 'http://www.gravatar.com/avatar/' + md5(self.email).hexdigest() + '?d=mm&s=' + str(size)

    def __repr__(self):
        return '<User %r>' % (self.nickname)

But I'm kinda lost as to why this would throw me an error. So my question is really: does anybody know what I' doing wrong here?

Any tips are welcome, since I'm totally lost..

Answer

jonrsharpe picture jonrsharpe · Jan 23, 2014

Nowhere in the block starting

if user is None:

do you actually assign anything to user, so it is still None and you get the error. Try changing to:

user = User(nickname = nickname, ...)

or call

user = User.select().where(User.email == resp.email).first()

again at the end of the if block