current_user in flask_login returns NoneType

Viewed 1905

In my forms.py app, I have the following lines:

from flask_wtf import FlaskForm
from wtforms import SelectField, StringField, SubmitField, TextAreaField, PasswordField, BooleanField
from wtforms.validators import DataRequired
from flask_login import current_user

class LogForm(FlaskForm):
    #game, title, log, submit
    game = SelectField(u'Select Game', default='', coerce=str, choices=[(game.game_name, game.game_name) for game in current_user.games])
    game.choices = [(game.game_name, game.game_name) for game in current_user.games]
    title = StringField('Title', validators=[DataRequired()])
    log = TextAreaField('Game log', validators=[DataRequired()])
    submit = SubmitField('Update')

class RegisterForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    email = StringField('Email', validators=[DataRequired()])
    password = PasswordField('Password', validators=[DataRequired()])

class LoginForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    password = PasswordField('Password', validators=[DataRequired()])
    remember_me = BooleanField("Remember me")
    submit = SubmitField("Sign in")

When I run my code, I get the following error:

>>> from app import db
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/AdityaD/iCloud Drive (Archive)/Desktop/flask_devlog/app/__init__.py", line 15, in <module>
    from app import routes, models
  File "/Users/AdityaD/iCloud Drive (Archive)/Desktop/flask_devlog/app/routes.py", line 7, in <module>
    from app.forms import LoginForm, LogForm
  File "/Users/AdityaD/iCloud Drive (Archive)/Desktop/flask_devlog/app/forms.py", line 7, in <module>
    print(current_user.id)
  File "/Users/AdityaD/iCloud Drive (Archive)/Desktop/flask_devlog/env/lib/python3.6/site-packages/werkzeug/local.py", line 347, in __getattr__
    return getattr(self._get_current_object(), name)
AttributeError: 'NoneType' object has no attribute 'id'

For reference, below are the relevant parts of the models.py file

from app import db
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
from app import login 

@login.user_loader
def load_user(id):
    return User.query.get(int(id))

class User(UserMixin, db.Model):
    __tablename__ = "User"
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64))
    hashed_password = db.Column(db.String(128))
    games = db.relationship('Game', backref='creator', lazy=True)

    def set_password(self, password):
        self.hashed_password = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.hashed_password, password)

    def __repr__(self):
        return f'<User {self.username}>'

I've tried to put an if statement containing something like if current_user is None to the LogForm form, but it still won't work. Why does this happen? Help!

Edit: Adding an is_authenticated check before the form statement returns AttributeError: 'NoneType' object has no attribute 'is_authenticated'

2 Answers

For flask_login to work you need to make sure that your code has the following method so that flask_login can actually log users given their id

@login_manager.user_loader
def load_user(user_id):
    return User.get(user_id)

In addition, for your form to correctly generate the game.choices field you need to ensure that you have a current_user object either by logging the user in.

To help you debug, try print(current_user) if you get an AnonymousUser object then it means your user wasn't properly logged in.

Same issue with mine. I realized that the current_user is AnonymousUserMixin while it is referenced inside the functions but it seems to appear as a NoneType object in the classes inherited from FlaskForm.

One alternative solution can be giving the current_user as an attribute to the LogForm, but I couldn't figure out how to do that.

Related