-1

I have a question, regarding my implementation of WTForms SelectMultipleField.

Whenever the form is submited, and the database is checked, I only find the first data inputed by the user, not the entire list. How could this implementation work for the whole list of submitted results?

This is what shows in the db

ID fav_colors
1 Blue
2 Red

And this is what should be shown per the user input

ID fav_colors
1 Yellow,Red,Blue
2 Red, Yellow

forms.py

class ColorForm(FlaskForm):
    fav_colors = SelectMultipleField(
            ' Select your Colors:',
             choices = [
                ( 1, 'Blue'),
                ( 2, 'Red'),
                ( 3, 'Yellow')
                 ])


routes.py

@route.('pick-your-color.html', methods=['GET', 'POST'])
def pick_your_color():
    form = ColorForm(request.form)

    form.fav_colors.data = None
    
    if request.method == "POST":

       fav_colors = request.form['fav_colors']
       register_colors = Colors(fav_colors = fav_colors)

       db.session.add(register_colors)
       db.session.commit()

       return render_template('index.html')

model.py

class Colors(db.Model):

    __tablename__ = "PickedColors"

    id = Column(integer, primary_key=True)
    fav_colors = Column(String)

pick-your-color.html


{% extendes "layout/base.html" %}

{{ form.fav_colors.label }}
{{ form.fav_colors(class="form-control", id=fav-colors") }}

{% block javascripts %}

//multiple select field
var selectStatesInputEl = d.querySelector('#fav-colors');
if(selectStatesInputE1) {
         const choices = new Choices(selectStatesInputE1);
}

{% endblock javascripts %}

P.S. I am using this JS so I can make it like the template I am using

1 Answers1

-1

The answer is quite simple:

  fav_colors = request.form.getlist('fav_colors')

There is a similar question to this problem @ Flask App Using WTForms with SelectMultipleField