Choices validation in WTForms does not update when database does

自闭症网瘾萝莉.ら 提交于 2019-12-04 08:28:30
Rachel Sanders

Yup - you got it. WTForms is a little unintuitive that way.

By the way, if you're pulling choices out of a SQLAlchemy database (and you're using Flask), check out the QuerySelectField addon:

http://wtforms.simplecodes.com/docs/0.6.1/ext.html#module-wtforms.ext.sqlalchemy

from wtforms.ext.sqlalchemy.fields import QuerySelectField

def all_employees():
  return Employee.query

class BugReportForm(Form):
  description = TextField(u"Notes")
  # The get_label will show the "name" attribute of the Employee model
  assign_to = QuerySelectField(u'Assign to',
                           get_label=u"name",
                           query_factory=all_employees)

That'll give you a Select field with the names of everybody.

Bonus: when you access BugReportForm.assign_to.data in the view code, it'll return the Employee object (not the id). It's handy.

No dummy, just don't put it in the class. Put it in the view code.

@app.route('/route')
def routename()
    form = SelectAThing()
    form.orgid.choices=get_joinable_orgs()

I found this tricky because I didn't realize I could assign to form like it was a regular python object after initializing it in the view.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!