I have separated model file and using app factory. The project structure is like this:
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
I have two models: article and category. Then, in forms.py
, I tried to do
like this:
class ArticleForm(Form):
title = StringField()
content = TextAreaField()
category = SelectField(
choices=[(c.id, c.name) for c in Category.query.all()]
)
So, Category.query.all()
is called outside app context and raising this:
RuntimeError: application not registered on db instance and no application
bound to current context
So, how can I populate the SelectField
with existing data on database?
You can use WTForms' QuerySelectField extension:
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With