okoboko
okoboko

Reputation: 4482

Flask + WTForms - Display Fields in FormList

I'm trying to build a form with dynamic fields (click a plus to add extra fields).

forms.py:

class ActionForm(Form):
    key = SelectField("Type: ", coerce=int, choices=[(0, "Option 1"), (1, "Option 2"), (2, "Opeion 3")], default=0)
    value = StringField('Value: ')


class EditForm(Form):
    content = StringField("Content: ")
    actions = FieldList(FormField(ActionForm))
    status = RadioField("Status: ", coerce=int, choices=[(0, "Inactive"), (1, "Active")], default=1)
    submit = SubmitField("Submit")

View Template (Won't Render the Fields from ActionForm):

<form method="POST">
{{ form.csrf_token }}
{{ form.actions.label }}
<div class="form-group input-group">
    {% for action in form.actions %}
        {% for field in action %}
            {{ field() }}
        {% endfor %}
    {% endfor %}
</div>
{{ form.status.label }}{{ form.status }}
{{ form.submit() }}
</form>

Problem:

In my form, I just see a blank spot where the ActionForm fields should appear.

In other words, I can't iterate through form.actions (to show the SelectField() and StringField()).

What am I doing wrong?

Upvotes: 3

Views: 3578

Answers (1)

Sean Vieira
Sean Vieira

Reputation: 159905

FieldList takes a min_entries keyword argument - if you set it, it will ensure that there are at least n entries:

class EditForm(Form):
    content = StringField("Content: ")
    actions = FieldList(FormField(ActionForm), min_entries=1)

Upvotes: 2

Related Questions