Closed tripdes closed 6 years ago
The problem is that the query for your categories runs in the global scope (i.e. when Python parses your script prior to running it), not when you create an instance of the form class.
You have two options to do this. You can either use the QuerySelectMultipleField
from the wtforms-sqlalchemy extension package, or else you have to move the initialization of the choices to the __init__()
function, so that it happens when the form instance is created. That would be more or less like this:
class ComposeForm(FlaskForm):
categories = SelectMultipleField('Categories', coerce=int)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.categories.choices=[(category.id, category.name.title()) for category in db.session.query(Category).all()]
@miguelgrinberg That's interesting regarding the categories running in the global scope. I came dangerously close to the example above but retreated as I thought I must be doing something wrong.
Thank you @miguelgrinberg, I really appreciate you taking the time in getting back to me! Hopefully this helps someone else as I could find very little online. Again, thanks for a great book, flask-migrate and I look forward to following your future projects.
Sam
Hi,
I've had alot of fun finishing your book and consider it a great refresh of the Oreilly book, but in my attempts to branch out I have encountered a minor issue when attempting to implement a Flask-WTF SelectMultipleField form with choices bound to a SQLAlchemy query.
Specifically when creating a SelectMultipleField in my
main
blueprint forms.py file:Now if I comment out the categories column and run
flask db init
my migrations folder is created successfully, however if I leave it I encounter the following error:The form is instantiated in my view but I'm trying to wrap my head around why the query is being executed now?
Any help would be greatly appreciated.
Sam