简体   繁体   English

flask_login 中的 current_user 返回 NoneType

[英]current_user in flask_login returns NoneType

In my forms.py app, I have the following lines:在我的 forms.py 应用程序中,我有以下几行:

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作为参考,下面是models.py文件的相关部分

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.我试图将包含if current_user is None类的 if 语句放入 LogForm 表单,但它仍然不起作用。 Why does this happen?为什么会发生这种情况? Help!帮助!

Edit: Adding an is_authenticated check before the form statement returns AttributeError: 'NoneType' object has no attribute 'is_authenticated'编辑:在表单语句返回之前添加 is_authenticated 检查AttributeError: 'NoneType' object has no attribute 'is_authenticated'

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要使flask_login 正常工作,您需要确保您的代码具有以下方法,以便flask_login 可以根据用户的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.此外,为了让您的表单正确生成game.choices字段,您需要通过登录用户来确保您拥有 current_user 对象。

To help you debug, try print(current_user) if you get an AnonymousUser object then it means your user wasn't properly logged in.为了帮助您调试,如果您获得AnonymousUser对象,请尝试print(current_user)则表示您的用户未正确登录。

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.我意识到 current_user 是 AnonymousUserMixin,而它在函数内部被引用,但它似乎在从 FlaskForm 继承的类中显示为 NoneType 对象。

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.一种替代解决方案可以将 current_user 作为 LogForm 的属性,但我不知道如何做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM