Dynamic choices WTForms Flask SelectField

The main idea here is to assign the choices list to the field after instantiation. To do so you need to use argument coerce=int. The coerce keyword arg to SelectField says that we use int() to coerce form data. The default coerce is unicode().

Correct FormModel:

class AddName(FlaskForm):
    name =StringField('Device name', validators=[InputRequired(),Length(min=4, max=30)])
    groupID = SelectField('Payload Type', coerce=int, validators=[InputRequired])

Correct View:

@app.route('/dashboard/addname', methods=['GET', 'POST'])
def addname():
    available_groups=db.session.query(Groups).filter(Groups.userID == currend_user.userID).all()
    #Now forming the list of tuples for SelectField
    groups_list=[(i.groupID, i.groupName) for i in available_groups]
    form=AddName()
    #passing group_list to the form
    form.groupID.choices = groups_list
    if form.validate_on_submit():
        name=Name(form.name.data,form.groupID.data)
        db.session.add(name)
        db.session.commit()
        return "New name added"

Leave a Comment