SelectField WTForms在表单提交时未返回所选值

时间:2019-11-06 07:44:41

标签: python python-3.x flask flask-sqlalchemy wtforms

我正在尝试创建一个SelectField来更改具有值(True,False)的用户验证状态,但是,该字段并没有改变返回的值,始终返回默认值,以下是代码表格。

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.")

在路由中,我试图从数据库中获取用户信息,以便以管理员身份对其进行编辑,但selectField会继续将此值设置为表单提交的结果,以下是该路由的代码。

@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
updateUserForm.status.data =  user.verified

if updateUserForm.validate_on_submit():
    user.username = updateUserForm.username.data
    user.email = updateUserForm.email.data
    user.verified = 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)

0 个答案:

没有答案