提问人:Usman Rafiq 提问时间:12/9/2018 最后编辑:Usman Rafiq 更新时间:12/9/2018 访问量:1071
AttributeError:“User”对象没有属性“email”
AttributeError: 'User' object has no attribute 'email'
问:
@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():
users = mongo.db.users
loginuser_json = users.find_one({'email': form.email.data})
if loginuser_json and bcrypt.check_password_hash(loginuser_json['password'], form.password.data):
# Create a custom user and pass it to login_user:
loginuser = User(loginuser_json)
login_user(loginuser,duration=d)
next_page = request.args.get('next')
return redirect(next_page) if next_page else redirect(url_for('home'))
return redirect(url_for('home'))
else:
flash('Login Unsuccessful. Please check username and password', 'danger')
return render_template('login.html', title='Login', form=form)
这是我为登录功能编写的代码,它工作正常
@app.route("/posts/new",methods=['GET', 'POST'])
@login_required
def new_post():
form=PostForm()
if form.validate_on_submit():
post = mongo.db.post
title=form.title.data
content=form.content.data
author=current_user.email
mypost={'title' : title, 'content' :content,'author':author}
post.insert(mypost)
flash('Your post has been created','success')
return redirect(url_for('home'))
return render_template('createpost.html', title='Create Post', form=form)
这是创建帖子并将其保存到 mongoDB 的代码,作者姓名是 loggedin
的current_user 此代码给出错误 AttributeError:“User”对象没有属性“email”
我该怎么办?
用户模型
class User(UserMixin):
def __init__(self, user_json):
self.user_json = user_json
# Overriding get_id is required if you don't have the id property
# Check the source code for UserMixin for details
def get_id(self):
object_id = self.user_json.get('email')
return str(object_id)
def get_mail(self):
return self.user_json.get('email')
答:
0赞
Ôrel
12/9/2018
#1
问题就在这里:
loginuser_json = users.find_one({'email': form.email.data})
你找email
但是你把它存储在àuthor
author=current_user.email
mypost={'title' : title, 'content' :content,'author':author}
使用以下方式更改商店:
mypost={'title' : title, 'content' :content,'email':author}
评论
0赞
Usman Rafiq
12/9/2018
author=current_user.email mypost={'title' : title, 'content' :content,'email':author} 像这样?
0赞
Usman Rafiq
12/9/2018
我写了你提到的解决方案的相同错误
0赞
Ôrel
12/9/2018
你能给出 的 值吗?loginuser_json
0赞
Usman Rafiq
12/9/2018
我已经找到了解决方案,我在用户类中创建了一个方法,并在后路由中使用该方法 感谢您的帮助
评论
User