【问题标题】:Validating Select Fields in Flask WTF Forms验证 Flask WTF 表单中的选择字段
【发布时间】:2012-06-06 20:11:05
【问题描述】:

我正在使用 Flask-WTF 表单,我有以下代码:

在forms.py中

class DealForm( Form ):
    country  = SelectField( 'Country' )

在 main.py 中

if not form.validate_on_submit():
    form = DealForm()
    form.country.choices = [('us','USA'),('gb','Great Britain'),('ru','Russia')]
    return render_template( 'index.html', user = current_user, form = form )
else:
    return render_template( 'index.html', form = form )

当我从 POST 返回时出现错误,因为 country.choices 是 None 我做错了什么?

【问题讨论】:

    标签: python flask wtforms


    【解决方案1】:

    您需要在调用validate_on_submit()之前设置选项。

    因为它们是静态的,所以在创建 Form 类时这样做:

    class DealForm(Form):
        country = SelectField('Country', choices=[
            ('us','USA'),('gb','Great Britain'),('ru','Russia')])
    

    如果您想在创建表单实例后设置它们,例如因为可用的选项不是硬编码的,也不是根据其他因素而有所不同,所以在创建类的实例后你会这样做:

    form.country.choices = [('us','USA'),('gb','Great Britain'),('ru','Russia')]
    

    即就像你之前所做的一样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-13
      相关资源
      最近更新 更多