我正在尝试将来自用户模型的数据(如用户名和电子邮件)填充到表单中,以便管理员可以使用在查询用户的路由中传递的user_id进行更新。但是我正在表单中进行自定义验证,以检查该字段是否未更改,以免出现使用用户名的错误。
当前,我正在使用Flask提供的g
全局变量来匹配要在表单验证功能中传递的路由中查询的用户obj数据。任何方式我都能做得更好??
下面是表单的代码:
class UpdateUserForm(FlaskForm):
username = StringField("Username", validators=[DataRequired()])
email = StringField("Email", validators=[DataRequired(), Email()])
status = SelectField("Account Status", choices=[(True, "Verified"), (False, "Not Verified")], coerce=bool, validators=[InputRequired()])
submit = SubmitField("Update")
def validate_username(self, username):
if username.data != g.username:
user = User.query.filter_by(username=username.data).first()
if user:
raise ValidationError("That username is taken, please choose a different one.")
def validate_email(self, email):
if email.data != g.email:
user = User.query.filter_by(email=email.data).first()
if user:
raise ValidationError("That email is taken, please choose a different one.")
这是路线的代码:
admin.route("/admin_panel/update_user/<int:user_id>", methods=['GET', 'POST'])
@admin_login_required
def update_user(user_id):
user = User.query.filter_by(id=user_id).first()
g.username = user.username
g.email = user.email
updateUserForm = UpdateUserForm()
updateUserForm.username.data = user.username
updateUserForm.email.data = user.email
print("this is first one" + str(updateUserForm.status.data))
if updateUserForm.validate_on_submit():
user.username = updateUserForm.username.data
user.email = updateUserForm.email.data
user.verified = updateUserForm.status.data
print("this is second one" + str(updateUserForm.status.data))
db.session.commit()
flash("Account updated!", 'success')
return redirect(url_for('admin.admin_panel'))
return render_template("admin/update_user.html", title="Update User", updateUserForm=updateUserForm)
不是我不能使用当前用户,因为管理员已登录