WTForms中的选择验证在数据库执行时不会更新

Mit*_*ops 5 python flask wtforms py2neo

我理解SelectFieldWTForms中的方法采用choices具有形式的can参数...

choices=[("value1", "display of value 1"), ("value2", "display of value 2")]
Run Code Online (Sandbox Code Playgroud)

我需要根据对数据库的调用来填充我的选择.我使用neo4j作为我的后端,所以我不能使用modelforms或其他内置解决方案来填充表单中的数据.

def get_list_of_things():
    query = 'start n = node:things("*:*") return ID(n), n.display_name;'
    t = cypher.execute(cdb, query)[0]
    for x in t:
        x[0] = str(x[0])
        x[1] = str(x[1])
    things = list(tuple(x) for x in t)
    return things

class SelectAThing(Form):
    thingID = SelectField('Thing name', choices=get_list_of_things())
Run Code Online (Sandbox Code Playgroud)

运行选项= get_list_of_things()确实产生了一个有效的选择列表,很棒,这基本上有效.

但是,即使数据库存在,也似乎永远不会更新事物列表,我稍后会返回该表单.如果我向db添加内容并返回,我仍然会看到第一个列表.

Rac*_*ers 7

是的 - 你明白了 WTForms就这样有点不直观.

顺便说一句,如果您从SQLAlchemy数据库中选择(并且您使用的是Flask),请查看QuerySelectField插件:

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)
Run Code Online (Sandbox Code Playgroud)

这将为您提供一个包含每个人姓名的选择字段.

额外奖励:当您在视图代码中访问BugReportForm.assign_to.data时,它将返回Employee对象(而不是id).它很方便.


Mit*_*ops 6

没有假人,只是不要把它放在课堂上。将其放在视图代码中。

@app.route('/route')
def routename()
    form = SelectAThing()
    form.orgid.choices=get_joinable_orgs()
Run Code Online (Sandbox Code Playgroud)

我发现这很棘手,因为在视图中对其进行初始化后,我没有意识到可以将其分配给它像是常规的python对象。