How to bind a field in __init__ function of a form

Leo*_*onF 1 python flask wtforms flask-wtforms

class Example_Form(Form):
    field_1 = TextAreaField()
    field_2 = TextAreaField()

    def __init__(self, type, **kwargs):
        super(Example_Form, self).__init__(**kwargs)

        if type == 'type_1':
           self.field_3 = TextAreaField()
Run Code Online (Sandbox Code Playgroud)

In some scenarios I need to dynamically add fields into the form. The field_3 added to example form turns out to be a UnboundField. I tried to bind field_3 to form in __init__ function, but it won't work.

field_3 = TextAreaField()
field_3.bind(self, 'field_3')
Run Code Online (Sandbox Code Playgroud)

How to bind field_3 to example form?

dav*_*ism 5

用于self.meta.bind_field创建绑定字段,并将其分配给实例和字典_fields

self.field_3 = self._fields['field_3'] = self.meta.bind_field(
    self, TextAreaField(),
    {'name': 'field_3', 'prefix': self._prefix}
)
Run Code Online (Sandbox Code Playgroud)

在大多数情况下,使用子类并在创建表单实例时决定使用哪个类会更清楚。

class F1(Form):
    x = StringField()

class F2(F1):
    y = StringField()

form = F1() if type == 1 else F2()
Run Code Online (Sandbox Code Playgroud)

如果您需要更加动态,您可以对表单进行子类化并为其分配字段。与实例不同,将字段分配给类可以直接进行。

class F3(F1):
    pass

if type == 3:
    F3.z = StringField()

form = F3()
Run Code Online (Sandbox Code Playgroud)

您还可以定义所有字段,然后选择在验证表单之前删除一些字段。

class F(Form):
    x = StringField()
    y = StringField()

form = F()

if type == 1:
    del form.y
Run Code Online (Sandbox Code Playgroud)