Dynamic choices WTForms Flask SelectField

后端 未结 1 1575
傲寒
傲寒 2020-12-01 17:06

I\'m trying to pass userID variable to WTForms with FlaskForms. First I\'ll show code that works fine and then what I need to modify(that the part I don\'t know how). I\'m a

相关标签:
1条回答
  • 2020-12-01 17:44

    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"
    
    0 讨论(0)
提交回复
热议问题