Flask - 如何在分离数据库文件时填充wtf表单中的select字段?

时间:2015-11-20 17:46:00

标签: flask

我已分离模型文件并使用app工厂。项目结构是 像这样:

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

我有两种模式:文章和类别。然后,在forms.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

那么,我如何用数据库中的现有数据填充SelectField

2 个答案:

答案 0 :(得分:2)

你可以使用WTForms' QuerySelectField扩展程序:

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())

答案 1 :(得分:1)

这篇博客文章帮助了我,因为我无法获得我想要的工作答案。也取消了导入。

http://kyle.marek-spartz.org/posts/2014-04-04-setting-wtforms-selection-fields-dynamically.html

我使用了他的第二种技术,问题看起来像

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()]