How do I edit a WTForms FieldList to remove a value in the middle of the list

Viewed 930

I am trying to create a screen that looks like this:

enter image description here

To do this I create a form (TemplateFormRow) and then put it into a FieldList item in a parent form (TemplateForm). My form code is as follows:

class TemplateFormRow(FlaskForm):
    col = StringField(label='Column Name')
    data_type = SelectField(label='Data Type',
                            choices=[("boolean", "boolean"), ("datetime", "datetime"),
                                     ("integer", "integer"), ("decimal", "decimal"), ("string", "string")])
    sequence = HiddenField()
    delete = SubmitField(label='Delete')


class TemplateForm(FlaskForm):
    rows = FieldList(unbound_field=FormField(TemplateFormRow), min_entries=1)
    add_row = SubmitField(label='Add Row')
    confirm = SubmitField(label='Confirm')

The goal is that when someone clicks the 'Delete' button on any row, I delete that row and present the form again without it. I finally got some Python / Flask code to make this work:

for ndx, this_row in enumerate(form.rows):
                if this_row.data['delete']:  # This was the row on which the person hit the delete button
                    # TODO: WTForms seems to say you shouldn't do the following, but it seems to work.
                    del form.rows.entries[ndx]
                    break

My problem is that the WTForms documentation for FieldList says, I think, that you're not supposed to do this...

Do not resize the entries list directly, this will result in undefined behavior. See append_entry and pop_entry for ways you can manipulate the list.

Their recommendations of using pop doesn't work for me as that pulls the last item off the list but I may need to pull the first, or a middle, item off.

So, what I'm doing works but, is it dangerous? Is there a better / approved way to do this? Thanks for your help!

1 Answers

https://github.com/wtforms/wtforms/issues/256#issuecomment-227610117 seems to be a possible solution to someone else who had the same problems as you. Removing entries not at the end of the list also seems to be behavior not implemented for FieldList. Since the documentation says not to remove directly from the internal list I would recommend working around that like the linked solution.

Related