flask wtforms selectfield 选择不更新
flask wtforms selectfield choices not update
class ArticleForm(Form):
type = SelectField('type', choices=[(h.id, h.name) for h in ArticleType.query.all()], coerce=int)
下面是我在视图中使用 ArticleForm 的方式
@admin.route('/article/add',methods=['get','post'])
def article_create():
article_form = ArticleForm()
我的问题是每次访问时 selectField 都没有读取数据库 /article/add
如果我在 ArticleType 中添加新类型,selectField 的选择将不会更新选择,直到我重新启动服务器。
但如果我像下面这样使用
@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()]
文章类型得到更新..
那么这有什么问题...
当我遇到这个问题时,我通过在我的表单 __init__
方法中填充选项来解决它
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
class ArticleForm(Form):
type = SelectField('type', choices=[(h.id, h.name) for h in ArticleType.query.all()], coerce=int)
下面是我在视图中使用 ArticleForm 的方式
@admin.route('/article/add',methods=['get','post'])
def article_create():
article_form = ArticleForm()
我的问题是每次访问时 selectField 都没有读取数据库 /article/add
如果我在 ArticleType 中添加新类型,selectField 的选择将不会更新选择,直到我重新启动服务器。
但如果我像下面这样使用
@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()]
文章类型得到更新.. 那么这有什么问题...
当我遇到这个问题时,我通过在我的表单 __init__
方法中填充选项来解决它
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