I'm trying to instantiate a Flask Form that contains a FieldList, for which I want to change the FormField based on an additional input parameter. Following this post , my setup looks like this:
class Child1(FlaskForm):
class Meta:
csrf = False
field = SelectField()
class Child2(FlaskForm):
class Meta:
csrf = False
field = StringField()
class Parent(FlaskForm):
field_list_form = FieldList(FormField(Child1))
def __init__(self, select_child="child1", *args, **kwargs):
super().__init__(*args, **kwargs)
if select_child == "child2":
self.field_list_form = FieldList(FormField(Child2))
Now in my Flask app, when I use the default parameter, doing this works fine
form = Parent()
for idx in range(42):
form.field_list_form.append_entry({})
But when doing
form = Parent(select_child="child2")
for idx in range(42):
form.field_list_form.append_entry({})
I get AttributeError: 'UnboundField' object has no attribute 'append_entry'
How should I do this differently?
This question seems to already have an answer here .
However, another solution is to wrap the class declaration with a function taking select_child
as an argument and, depending on the argument value, create the FormField with either of your Child classes.
In your case, it would be:
def create_parent(select_child="child1"):
class Parent(FlaskForm):
if select_child == 'child1':
field_list_form = FieldList(FormField(Child1))
elif select_child == "child2":
field_list_form = FieldList(FormField(Child2))
return Parent()
Then form = Parent(select_child="child2")
becomes form = create_parent(select_child="child2")
Further details in this answer .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.