WTForms 表单动态验证

class UserDetails(Form):
    group_id = SelectField(u'Group', coerce=int)

def edit_user(request, id):
    user = User.query.get(id)
    form = UserDetails(request.POST, obj=user)
    form.group_id.choices = [(g.id, g.name) for g in Group.query.order_by('name')]

choices是SelectField的内置属性

Note:

  Note we didn’t pass a choices to the SelectField constructor, but rather created the list in the view function. Also, the coerce keyword arg to SelectField says that we use int() to coerce form data. The default coerce is unicode().

值得注意的是:

  我们不需要把choices传递到SelectField构造器中,而是在view中直接创造一个嵌套list(key,value)。并且,关键字coerce表明我们把表单中的数据强制规定为int

 

你可能感兴趣的:(WTForms 表单动态验证)