1

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.