如何修复“用户”对象没有属性“ is_active”?

时间:2019-05-26 09:44:59

标签: flask

我的login_user(user)函数不起作用,每次我登录此错误都会引发AttributeError:'User'对象没有属性'is_active'

我认为我的user_loader函数始终不返回

这是我的模型。py

from flask_login import UserMixin 
from datetime import datetime
from flaskblog import db,login_manager


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

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    image_file = db.Column(db.String(20), nullable=False, default='default.jpg')
    password = db.Column(db.String(60), nullable=False)
    posts = db.relationship('Post', backref='author', lazy=True)

这是我的路线

@app.route("/login",methods=['GET','POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user and bcrypt.check_password_hash(user.password,form.password.data):
            login_user(user)
            flash(f'You have been loged in','success')
            return redirect(url_for('home'))
        else:
            flash(f'cheack email and password','danger')
    return render_template('Login.html', title='login', form=form)

Flask_blog / flaskblog / routes.py”,第60行,登录 login_user(用户)

2 个答案:

答案 0 :(得分:0)

我曾经遇到过同样的麻烦,但是我通过使用以下代码解决了它。

@app.route("/login", methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(phone=form.phone.data).first()
        if user and bcrypt.check_password_hash(user.password, form.password.data):
            login_user(user, remember=form.remember.data)
            next_page = request.args.get('next')
            return redirect(next_page) if next_page else redirect(url_for('home'))
        else:
            flash('Login Unsuccessful. Please check email and password', 'danger')
    return render_template('login.html', title='Login', form=form)

型号:

class User(db.Model, UserMixin):
    __bind_key__ = 'user'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(20), unique=True, nullable=False)
    phone = db.Column(db.String(12), unique=True, nullable=False) 
    IDcard = db.Column(db.String(20), unique=True, nullable=False)
    age = db.Column(db.String(3), unique=True, nullable=False)
    password = db.Column(db.String(60), nullable=False) 

答案 1 :(得分:0)

您没有使用AnonymousMixin

定义AnonymousUser
login_manager.anonymous_user = AnonymousUser

this project

所示