在SelectField flask-WTForms中初始化后设置默认值 [英] Setting default value after initialization in SelectField flask-WTForms

查看:135
本文介绍了在SelectField flask-WTForms中初始化后设置默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to pre-select the value for SelectField when displaying it to user. default argument works when it is passed at the time of instantiation but does not work once the field is initialized.

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

当我尝试使用 default 值预选选项,然后再将表单提交给用户进行编辑时,它将不起作用.

When I try to use default value to preselect option before presenting the form to user for editing, it doesn't work.

address_form = AddressForm()
address_form.country.default='US'    # doesnot work

需要一种解决方案,以便在向用户展示之前将默认值设置为预设值.

Need a solution to set default value to pre-set values before presenting to the user.

方案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

推荐答案

一旦创建了表单实例,便会绑定数据.在那之后更改默认值无济于事.更改 choices 起作用的原因是因为它会影响验证,直到调用 validate 时该验证才会运行.

Once an instance of the form is created, the data is bound. Changing the default after that doesn't do anything. The reason changing choices works is because it affects validation, which doesn't run until validate is called.

将默认数据传递到表单构造器,它将用于如果未传递任何表单数据.如果用户不更改该值,则默认值将是第一次呈现,然后第二次发布.

Pass default data to the form constructor, and it will be used if no form data was passed. The default will be rendered the first time, then posted the second time if the user doesn't change the value.

form = AddressForm(request.form, country='US')

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

(If you're using Flask-WTF's Form you can leave out the request.form part.)

这篇关于在SelectField flask-WTForms中初始化后设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆