Forums

[Flask] current_user problem

Hi,

I have this problem that it only occur when I deploy it here in pythonanywhere, it works fine on my local machine. It seems the current_user.isactive is True by default. but when run locally it's False.

index.html

{% block content %}
{% if current_user.is_active %}
    <li><a href="/users">Users</a></li>
    <li><a href="/logout">Log out [{{ current_user.name }}]</a></li>
 {% else %}
    <li><a href="/login">Log in</a></li>
    <li><a href="/register">Sign up</a></li>
    <li><a href="#">Gallery</a></li>
{% endif %}
 ...

User model

class User(db.Model):
__tablename__ = "users"

id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), unique=True)
email = db.Column(db.String(150), unique=False)
password = db.Column(db.String(150))

def __init__(self, name=None, email=None, password=None):
    self.name = name
    self.email = email
    self.password = bcrypt.generate_password_hash(password)

def is_authenticated(self):
    return True

def is_active(self):
    return True

def is_anonymous(self):
    return False

def get_id(self):
    return unicode(self.id)

def __repr__(self):
    return '<name - {}>'.format(self.name)

Any help are greatly appreciated.

Thanks.

That sounds weird. Are you sure you have restarted your webapp with the correct code?

Yes. I restarted it a couple of times. It's quite frustrating since it's working fine if run locally.

Just to confirm, is_active is a function on the model class that always returns True? and it's not a database field or anything?

I used the Flask-login extension. Basically I followed what's being done here: https://realpython.com/blog/python/using-flask-login-for-user-management-with-flask/

In that tutorial it says all users are active, always return true.

It was my understanding that the users are active if it's successfully login.

from the tutorial

has an is_active() method that returns True if the user’s account is active

I also tried the is_authenticated but still it wont work.

Both changes work perfectly when run on my local machine but it wont work here.

something is wrong on your local machine. or you are not following the tutorial you linked me exactly. look at the code that I am copy and pasting from the tutorial:

def is_active(self):
    """True, as all users are active."""
    return True

Thanks conrad. There's nothing wrong with the code, I just updated myvirtualenv to used the latest flask-login

pip install flask-login --upgrade

Now it's working fine.

You should consider using the {{ url_for() }} helper in your templates to generate your URLs. You will love your life and code a lot more.