How to bind a field in __init__ function of a form

我的梦境 提交于 2019-12-13 17:24:50

问题


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()

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')

How to bind field_3 to example form?


回答1:


Use self.meta.bind_field to create a bound field, and assign it to the instance and the _fields dict.

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

In most cases, it's more clear to use a subclass and decide which class to use when creating the form instance.

class F1(Form):
    x = StringField()

class F2(F1):
    y = StringField()

form = F1() if type == 1 else F2()

If you need to be more dynamic, you can subclass the form and assign fields to it. Assigning fields to classes works directly, unlike with instances.

class F3(F1):
    pass

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

form = F3()

You can also define all fields, then choose to delete some before validating the form.

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

form = F()

if type == 1:
    del form.y


来源:https://stackoverflow.com/questions/43267820/how-to-bind-a-field-in-init-function-of-a-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!