Dynamic select field using WTForms not updating

后端 未结 2 818
太阳男子
太阳男子 2020-12-15 02:08

I\'m trying to make a dynamic select field using wtforms and sqlalchemy, but it doesn\'t update when an item is inserted or deleted from the database. Here\'s my code:

相关标签:
2条回答
  • 2020-12-15 02:34

    It's worth mention that part of the answer of @plaes is wrong

    def __init__(self, *args, **kwargs):
            super(UserForm, self).__init__(*args, **kwargs)
            self.job.choices = [(a.id, a.name) for a in Job.query.order_by(Job.name)]
    

    in the init func we should call super first .then use self.job.choices or it will not work..

    see my question here flask wtforms selectfield choices not update

    0 讨论(0)
  • 2020-12-15 02:44

    You should initialize the form choices when the form object is created:

    class UserForm(Form):
        username = StringField('Username', validators=[DataRequired()])
        password = PasswordField('Password', validators=[DataRequired()])
        job = SelectField(
            'Job',
            validators=[DataRequired()]
        )
    
        def __init__(self, *args, **kwargs):
            super(UserForm, self).__init__(*args, **kwargs)
            self.job.choices = [(a.id, a.name) for a in Job.query.order_by(Job.name)]
    

    Or in the view:

    form = UserForm()
    form.job.choices = [(a.id, a.name) for a in Job.query.order_by(Job.name)]
    
    0 讨论(0)
提交回复
热议问题