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?
Use
self.meta.bind_field
to create a bound field, and assign it to the instance and the_fields
dict.In most cases, it's more clear to use a subclass and decide which class to use when creating the form instance.
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.
You can also define all fields, then choose to delete some before validating the form.