Flask-当数据库文件被分离时,如何在wtf表单中填充select字段?
我已经分离模型文件和使用应用程序工厂。项目结构如下: 像这样:Flask-当数据库文件被分离时,如何在wtf表单中填充select字段?,flask,Flask,我已经分离模型文件和使用应用程序工厂。项目结构如下: 像这样: project/ |-- config.py |-- core.py # app factory definition which calls db.init_app(app) |-- database.py # models definition and 'db = SQLAlchemy()' is done here |-- forms.py # forms definition. |-- __init__.
project/
|-- config.py
|-- core.py # app factory definition which calls db.init_app(app)
|-- database.py # models definition and 'db = SQLAlchemy()' is done here
|-- forms.py # forms definition.
|-- __init__.py # app = create_app() is done here
\-- routes.py
class ArticleForm(Form):
title = StringField()
content = TextAreaField()
category = SelectField(
choices=[(c.id, c.name) for c in Category.query.all()]
)
我有两个模型:文章和类别。然后,在forms.py
中,我尝试
像这样:
project/
|-- config.py
|-- core.py # app factory definition which calls db.init_app(app)
|-- database.py # models definition and 'db = SQLAlchemy()' is done here
|-- forms.py # forms definition.
|-- __init__.py # app = create_app() is done here
\-- routes.py
class ArticleForm(Form):
title = StringField()
content = TextAreaField()
category = SelectField(
choices=[(c.id, c.name) for c in Category.query.all()]
)
因此,Category.query.all()
在应用程序上下文外部调用,并引发以下问题:
RuntimeError: application not registered on db instance and no application
bound to current context
那么,如何使用数据库中的现有数据填充选择字段?您可以使用WTForms的扩展:
from flask_wtf import Form
from wtforms.fields import StringField, TextAreaField
from wtforms.ext.sqlalchemy.fields import QuerySelectField
from database import Category
class ArticleForm(Form):
title = StringField()
content = TextAreaField()
category = QuerySelectField(query_factory=lambda: Category.query.all())
这篇博文帮助了我,因为我无法得到我想要的工作的公认答案。也可以删除导入
我使用了他的第二种技巧,对于这个问题
from flask_wtf import Form
from wtforms.fields import StringField, TextAreaField
from database import Category
class ArticleForm(Form):
title = StringField()
content = TextAreaField()
category = SelectField()
def __init__(self):
super(ArticleForm, self).__init__()
self.category.choices = [(c.id, c.name) for c in Category.query.all()]
这个语法对我不起作用,所以我不得不调整它为:def uuu init_uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu