【问题标题】:Flask-WTForms Set Default for Render Template but Ignore in ValidationFlask-WTForms 为渲染模板设置默认值,但在验证时忽略
【发布时间】:2015-12-18 18:38:18
【问题描述】:

我有一个表单类,我设置了默认值(用户当前信息),以便它预先填充表单。但是,这会导致验证问题,因为在 Required() 的情况下,它接受默认值作为输入。但是, InputRequired() 似乎解决了这个问题,但它没有正确验证 Email()。它似乎接受任何输入...

如何使用用户当前数据预先填充表单,但只提交当前值进行验证?

#My Form Class
class UserInfoForm(Form):
    id = HiddenField('Employee ID')
    fullName = TextField('Full Name', validators=[InputRequired()])
    position = SelectField('Employee Position', coerce=int)
    email = TextField('Email Address', validators=[InputRequired(), Email()])
    password = PasswordField(
        'New Password',
        validators=[EqualTo('confirm', message='Passwords must match.')])
    confirm = PasswordField('Repeat Password')

#My View
form = UserInfoForm()
form.position.choices = [(p.id, p.title) for p in EmpPosition.query.order_by('id')]
form.position.default = current_user.position.id
form.fullName.default = current_user.fullName
form.email.default = current_user.email
form.process()
if form.validate_on_submit():
    #Submit to DB
return render_template('profile.html', data=data, form=form)

【问题讨论】:

  • 你试过DataRequired()吗?
  • 不是真的,而是因为文档明确说它会寻找后强制,而 InputRequired 会寻找来自表单的实际输入。
  • 如果数据已经可供当前用户使用,为什么还要通过表单提交呢?你不能把它添加到后端的数据库中吗?
  • 啊,我应该更清楚目的。我试图允许用户“编辑”那里的用户个人资料。所以我需要用他们当前的数据预填充表单,然后验证任何更改。我已经使用 ajax 成功完成了这项工作,但我正在尝试仅使用可用的实用程序来完成这项工作。

标签: python validation flask flask-wtforms


【解决方案1】:
form = UserInfoForm()

if form.validate_on_submit():
    current_user.fullName = form.fullname.data
    current_user.position = form.position.data
    current_user.email = form.email.data
    current_user.password = form.password.data
    ... your db stuff here ...
    ... and whatever else you want to do afterwards ...

form.fullname.data = current_user.fullName
form.position.data = current_user.position
form.email.data = current_user.email
form.password.data = current_user.position

return render_template('profile.html', data=data, form=form)

唯一的另一件事是您需要向表单提交字段。

参考:Miguel Grinberg 的 Flask Web Development

【讨论】:

  • 啊,好吧,所以我只需要把它放在 if 语句之后。有道理......所以我应该能够使用Required而不是更具体的类。
猜你喜欢
  • 2022-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
  • 2016-07-09
  • 1970-01-01
  • 2012-08-19
  • 2021-09-06
相关资源
最近更新 更多