Home > Net >  Flask Wtforms FieldList(FormField to populate a SelectField with choices is not appending to form
Flask Wtforms FieldList(FormField to populate a SelectField with choices is not appending to form

Time:08-13

I am trying to populate a form using a combination of str and lists. The string fields in the form populate without issue. However the selectfield in the form appears to only display the last entry given in the list it receives as if it's overwritten the previous contents in the form.

If the list (later converted to tuple) is : [['[email protected]', '[email protected]'], ['[email protected]', '[email protected]]]

What gets displayed in the choices throughout the form will be:

[email protected] [email protected]

I've tried various iterations but no luck so far.

    class BulkAddFields(Form):
    ip_addr = StringField(label='ip_addr')
    dom_emails = StringField('dom_emails')
    new_emails = SelectField('new_emails', coerce=int)
  
    class BulkAddForm(FlaskForm):
    incidents = FieldList(FormField(BulkAddFields))
    submit = SubmitField('Submit')
    
    form = BulkAddForm()
    # i = str, d = str, n=list
    for i, d, n, in data:
        form.ip_addr = i
        form.dom_emails = d
        form.incidents.append_entry(form) 
        email = list(enumerate(n))
        for sub_form in form.incidents:
            sub_form.new_emails.choices = email

I've added a picture/link that shows how the string fields are replicated down the page as expected but the selectfield replicates the last item in the list only.

enter image description here

CodePudding user response:

Try changing it from

new_emails = SelectField('new_emails', coerce=int)

to

new_emails = SelectField('new_emails', coerce=str)

You should then be able to pass the choices as a list. Let me know if that helps.

CodePudding user response:

Below is the code that ended up working. Although I don't like adding a field to the form each time, knowing that the field is going to exist everytime I wanted to include it in the BulkAddFields but couldn't figure out how.

class BaseForm(FlaskForm):
    @classmethod
    def append_field(cls, name, field):
        setattr(cls, name, field)
        return cls

class BulkAddFields(BaseForm):
    ip_addr = StringField(label='ip_addr')
    dom_emails = StringField('dom_emails')

class BulkAddForm(BaseForm):
    incidents = FieldList(FormField(BulkAddFields))
    submit = SubmitField('Submit')

form = BulkAddForm()
    for i, d, n, in data:
        email = list(enumerate(n))
        bulkfields = BulkAddFields()
        bulkfields = bulkfields.append_field('new_emails',
                SelectField('New Emails', choices=email))
        form.ip_addr = i
        form.dom_emails = d
        
        form.incidents.append_entry(form)

Picture with repeating selectfield for New Emails

  • Related