Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask - How to populate select field in wtf form when database files is separated?

Tags:

flask

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?

like image 771
Mas Bagol Avatar asked Dec 05 '22 01:12

Mas Bagol


1 Answers

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())
like image 76
Dauros Avatar answered May 22 '23 23:05

Dauros