flask wtforms selectfield选项未更新 [英] flask wtforms selectfield choices not update
本文介绍了flask wtforms selectfield选项未更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class ArticleForm(Form):
type = SelectField('type', choices=[(h.id, h.name) for h in ArticleType.query.all()], coerce=int)
下面是我如何在视图中使用ArticleForm
below is how I use the ArticleForm in views
@admin.route('/article/add',methods=['get','post'])
def article_create():
article_form = ArticleForm()
我的问题是,每次我访问/article/add时,selectField都不会读取db
my problem is that the selectField is not read the db each time I visit /article/add
如果我在ArticleType中添加了新类型,则在重新启动服务器之前,selectField的选择将不会更新该选择.
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()]
articleType得到更新. 那么这是什么问题...
the articleType get updated.. so what's the problem with this...
推荐答案
当我遇到此问题时,我会通过填充__init__
我的Form方法中的选项来解决它
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
这篇关于flask wtforms selectfield选项未更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文