在SelectField flask-WTForms中初始化后设置默认值

ebd*_*ebd 4 python flask wtforms

我想SelectField在向用户显示时预先选择值.default参数在实例化时传递,但在初始化字段后不起作用.

class AddressForm(Form):
    country = SelectField('Country',choices=[('GB', 'Great Britan'), ('US', 'United States')], default='GB')    # works
Run Code Online (Sandbox Code Playgroud)

当我default在将表单呈现给用户进行编辑之前尝试使用值来预选选项时,它不起作用.

address_form = AddressForm()
address_form.country.default='US'    # doesnot work
Run Code Online (Sandbox Code Playgroud)

需要一种解决方案,在呈现给用户之前将默认值设置为预设值.

场景2:也不起作用

class AddressForm(Form):
        country = SelectField('Country')    # works

address_form = AddressForm()
address_form.country.choices=[('GB', 'Great Britan'), ('US', 'United States')]
address_form.country.default='US'    # doesnot work
Run Code Online (Sandbox Code Playgroud)

dav*_*ism 7

创建表单实例后,绑定数据.之后更改默认值不会执行任何操作.更改choices工作的原因是因为它影响验证,validate在调用之前不会运行.

将默认数据传递给表单构造函数,如果没有传递表单数据,将使用它.默认值将在第一次呈现,然后在用户未更改值时第二次发布.

form = AddressForm(request.form, country='US')
Run Code Online (Sandbox Code Playgroud)

(如果您使用的是Flask-WTF Form,则可以省略该request.form部分.)


小智 5

我知道你可能解决了这个问题。但我认为它不再起作用了。因为这是在 google 上搜索问题时出现的第一件事,所以我想为有这个问题的人提供一个可行的解决方案(至少对我而言)。

要确认默认选择的更改,我们必须添加address_form.process() . 就是这样!

完整的解决方案是:

class AddressForm(Form):
        country = SelectField('Country')    # works

address_form = AddressForm()
address_form.country.choices=[('GB', 'Great Britan'), ('US', 'United States')]
address_form.country.default='US'
address_form.process()    # works
Run Code Online (Sandbox Code Playgroud)