AttributeError: 'SelectQuery' object has no attribute 'is_active'
Asked Answered
P

1

5

I'm trying to learn the Peewee ORM in combination with Flask by following the Flask Mega Tutorial. In part 5 of the tutorial I create a login using OpenID. After overcoming a bunch of hurdles already I now get an AttributeError in the function pasted below on the following line: 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)    
    if user.wrapped_count() == 0:
        nickname = resp.nickname
        if nickname is None or nickname == "":
            nickname = resp.email.split('@')[0]
        user = User(nickname = nickname, email = resp.email, role = models.ROLE_USER)
        user.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'))

is_active is found in my User model as follows:

class User(db.Model):
    nickname = TextField()
    email = TextField()
    role = IntegerField(default = ROLE_USER)

    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 __repr__(self):
        return '<User %r>' % (self.nickname)

I have no clue what I'm doing wrong here though. Could anybody give me a helping hand in what I'm doing wrong here?

All tips are welcome!

Parrnell answered 15/1, 2014 at 14:22 Comment(0)
P
12

As the error suggests, user = User.select().where(User.email == resp.email) gives you back a SelectQuery, not an instance of User. You'll want to include an additional method call to actually fetch the record, something like .first(). first will return either an instance of User or None.

This would allow you to slightly adjust your code:

user = User.select().where(User.email == resp.email).first()
if not user:  # or if user is None:
    nickname = resp.nickname
    ...
Prescript answered 15/1, 2014 at 16:17 Comment(1)
I'm new to peewee, but I think currently the equivalent of first() is get()Pastorate

© 2022 - 2024 — McMap. All rights reserved.