flask wtforms selectfield choices not update

最后都变了- 提交于 2019-12-06 16:41:47

问题


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


来源:https://stackoverflow.com/questions/36515009/flask-wtforms-selectfield-choices-not-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!