[英]Flask-SQLalchemy update the current_user
How would I update the current users firstname and lastnames in my Flask-SQLAlchemy database?如何更新我的 Flask-SQLAlchemy 数据库中当前用户的名字和姓氏?
I have tried to use the following code based off of the flask-sqlalchemy documentation - however, it only commits the update for the email field and does not update the record for either the firstname or lastname fields.我尝试使用基于 flask-sqlalchemy 文档的以下代码 - 但是,它只提交 email 字段的更新,而不更新名字或姓氏字段的记录。
# views.py
@users.route("/account", methods=['GET', 'POST'])
@login_required
def account():
form = UpdateUserForm()
if form.validate_on_submit():
current_user.firstname = form.firstname.data
current_user.lastname = form.lastname.data
current_user.email = form.email.data
db.session.commit()
return redirect(url_for('users.account'))
elif request.method == 'GET':
form.firstname.data = current_user.firstname
form.lastname.data = current_user.lastname
form.email.data = current_user.email
return render_template('account.html', form=form)
#forms.py
class UpdateUserForm(FlaskForm):
email = StringField('Email',validators=[InputRequired(message = 'Enter a valid email'),Email()])
firstname = StringField('First Name',validators=[InputRequired(message = 'Enter your first name')])
lastname = StringField('Last Name',validators=[InputRequired(message = 'Enter your last name')])
submit = SubmitField('Update')
def validate_email(self,email):
if User.query.filter_by(email=email.data).first():
raise ValidationError('This email has been registered already!')
# Summarized Template & Form Submission
<div class="tab-content" id="myTabContent">
<div class="tab-pane fade show active" id="account" role="tabpanel" aria-labelledby="account-tab">
<div class="col-5">
</div>
<div class="col-sm-12 col-md-7">
<form method="post" action="" enctype="multipart/form-data">
{{ form.hidden_tag() }}
<div class="form-group">
<label class="small mb-0">{{ form.firstname.label }}</label>
{{ form.firstname(class="form-control") }}
</div>
<div class="form-group">
<label class="small mb-0">{{ form.lastname.label }}</label>
{{ form.lastname(class="form-control") }}
</div>
<div class="form-group">
<label class="small mb-0">{{ form.email.label }}</label>
{{ form.email(class="form-control") }}
</div>
{{ form.submit(class="btn btn-primary") }}
</form>
</div>
</div>
# Model.py
class User(db.Model, UserMixin):
__tablename__ = 'users'
id = db.Column(db.Integer,primary_key=True)
selected_theme = db.Column(db.String(64),nullable=False,default='default')
email = db.Column(db.String(64),unique=True,index=True)
fullname = db.Column(db.String(64))
firstname = db.Column(db.String(64))
lastname = db.Column(db.String(64))
password_hash = db.Column(db.String(128))
def __init__(self,email,fullname,password, firstname, lastname):
self.email = email
self.fullname = fullname
self.firstname = firstname
self.lastname = lastname
self.password_hash = generate_password_hash(password)
def check_password(self,password):
return check_password_hash(self.password_hash,password)
def __repr__(self):
return f"Username {self.username}"
Sorry, I can't find a mistake.抱歉,我找不到错误。 The following code works for me.
以下代码适用于我。 Even if there is no real difference to yours, it is worth trying.
即使与您的没有真正的区别,也值得尝试。
class UpdateUserForm(FlaskForm):
email = StringField(
'Email',
validators=[
# InputRequired is deprecated and replaced by DataRequired
DataRequired(message = 'Enter a valid email'),
Email()
]
)
firstname = StringField(
'First Name',
validators=[
DataRequired(message = 'Enter your first name')
]
)
lastname = StringField(
'Last Name',
validators=[
DataRequired(message = 'Enter your last name')
]
)
submit = SubmitField('Update')
def validate_email(self, email):
if User.query.filter_by(email=email.data).first():
raise ValidationError('This email has been registered already!')
@users.route("/account", methods=['GET', 'POST'])
@login_required
def account():
# You can forward your current data to the form here
form = UpdateUserForm(request.form, obj=current_user)
if form.validate_on_submit():
current_user.firstname = form.firstname.data
current_user.lastname = form.lastname.data
current_user.email = form.email.data
db.session.commit()
return redirect(url_for('users.account'))
return render_template('account.html', **locals())
<form method="POST">
{{ form.csrf_token }}
<div class="form-group">
{{ form.email.label() }}
{{ form.email(class='form-control') }}
{% if form.email.errors: %}
<div class="invalid-feedback">
{{ form.email.errors[0] }}
</div>
{% endif %}
</div>
<div class="form-group">
{{ form.firstname.label() }}
{{ form.firstname(class='form-control') }}
{% if form.firstname.errors: %}
<div class="invalid-feedback">
{{ form.firstname.errors[0] }}
</div>
{% endif %}
</div>
<div class="form-group">
{{ form.lastname.label() }}
{{ form.lastname(class='form-control') }}
{% if form.lastname.errors: %}
<div class="invalid-feedback">
{{ form.lastname.errors[0] }}
</div>
{% endif %}
</div>
{{ form.submit(class='btn btn-primary') }}
</form>
Thanks for your help.谢谢你的帮助。 Was able to resolve my issue by including the following updated to ignore the email submission if it is unchanged (I think it was recognized as a duplicate record and preventing unique value).
能够通过包含以下更新来解决我的问题,以忽略 email 提交(如果它未更改)(我认为它被识别为重复记录并防止唯一值)。 This little addition seems to resolve.
这个小小的补充似乎解决了。
def validate_email(self,email):
if User.query.filter_by(email=email.data).first() and email.data != current_user.email:
raise ValidationError('Email has been already been registered.')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.