1

I implemented WTForm's FieldList with SelectField's to render multiple select choices based on data in a JSON file (as stated in this answer). It displays the select choices fine, but when I try to pass all the values that the user selected via a SubmitField() form, the request only contains the value from the first one.

Question: How can I access ALL the selected values from my multiple SelectFields from my route?

Interesting Note:

  • I did this same FieldList approach with multiple StringFields and get each of the values as expected in the request. (Why would this be different for SelectFields?)

The multiple select fields: enter image description here

  • Here Ford, Associate, and Bucks are the values from the select fields.

The request response: (from request.form): enter image description here

  • Notice how only Ford is shown. Why not also Associate and Bucks?
  • Notice how all the text fields show up correctly

My forms (forms.py):

class SelectForm(FlaskForm):
    select = SelectField(choices=[]) #TODO testing without placeholder


class SelectFormList(FlaskForm):
    """A form that supports multiple select forms"""
    select_entries = FieldList(FormField(SelectForm))

My template (home.html):

<form id="metadata_home_fom" action="{{ url_for('save_metadata') }}" method="POST">

    {% for select_form in select_metadata_form_list.select_entries %}
        {{ select_form.hidden_tag() }}
        {{ select_form.select.label }}: {{ select_form.select }}
    {% endfor %}

    {% for text_form in text_metadata_form.text_fields %}
        {{ text_form.hidden_tag() }}
        {{ text_form.text }}
    {% endfor %}
</form>


My view (routes.py):

@app.route('/home', methods=['POST', 'GET'])
def home():
    select_metadata_form_list = SelectFormList()
    select_metadata_form_list.select_entries = get_select_entries()

        context = {"text_metadata_form": text_metadata_form,
        "select_metadata_form_list": select_metadata_form_list}

    return render_template('configuration.html', **context)
Tyler Dane
  • 951
  • 1
  • 14
  • 25

1 Answers1

0

The problem was I was creating my forms in a loop without overriding the form's name, so each of the SelectFields had the same name.

The quick fix was just appending a unique id to the name:

        for k, v in select_dict.items():
            some_id = uuid.uuid1()
            select_entry = SelectForm()
            select_entry.select.name = f"select_entry-{some_id}" # each SelectForm() unique
            select_entry.select.label = k
            select_entry.select.choices = v
            all_select_items.append(select_entry)
Tyler Dane
  • 951
  • 1
  • 14
  • 25