flask wtforms selectfield choices not update

2020-06-30 04:24发布

问题:

class ArticleForm(Form):
    type = SelectField('type', choices=[(h.id, h.name) for h in ArticleType.query.all()], coerce=int)

below is how I use the ArticleForm in views

@admin.route('/article/add',methods=['get','post'])
def article_create():
    article_form = ArticleForm()

my problem is that the selectField is not read the db each time I visit /article/add

If I add a new type in the ArticleType the choice of the selectField will not update the choice until I restart the server.

but If I use like below

@admin.route('/article/add',methods=['get','post'])
def article_create():
    article_form = ArticleForm()
    article_form.type.choices = [(h.id, h.name) for h in ArticleType.query.all()]

the articleType get updated.. so what's the problem with this...

回答1:

When I met this problem I resolve it with populating choices in __init__ method of my Form

class ArticleForm(Form):
    type = SelectField()

    def __init__(self, *args, **kwargs):
        form = super(ArticleForm, self).__init__(*args, **kwargs)
        form.type.choices = [(h.id, h.name) for h in ArticleType.query.all()]
        return form