【问题标题】:Choices validation in WTForms does not update when database does当数据库更新时,WTForms 中的选项验证不会更新
【发布时间】:2012-11-26 17:24:09
【问题描述】:

我了解 WTForms 中的 SelectField 方法采用可以参数 choices 的形式...

choices=[("value1", "display of value 1"), ("value2", "display of value 2")]

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

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())

运行选项 = get_list_of_things() 确实会生成一个有效的选项列表,很好,这基本上可以工作。

然而,它似乎永远不会更新事物列表,即使数据库更新了,我稍后会返回该表单。如果我将东西添加到数据库并返回,我仍然会看到第一个东西列表。

【问题讨论】:

    标签: python flask wtforms py2neo


    【解决方案1】:

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

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

    我发现这很棘手,因为我没有意识到在视图中初始化它之后,我可以像普通 python 对象一样分配给表单。

    【讨论】:

      【解决方案2】:

      是的 - 你明白了。 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)
      

      这将为您提供一个包含每个人姓名的 Select 字段。

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

      【讨论】:

      • 这非常有用。我希望 sqlalchemy 支持 neo4j,所以我可以使用它。
      【解决方案3】:

      我有同样的问题,我尝试了 QuerySelectField 但因为它不是“选择输入”并且它是一个 ul 元素,它不能接受像 onchange 这样的事件并且很难用 JavaScript 获取值,所以我必须保留selectField 字段,并且由于它不是自定义路径并且这是模态 View ,因此我在渲染函数中更新了 kawargs['form'].column.choices 并关闭了 selectField 的验证以接受更新的街道而无需重新加载应用程序

      form_extra_fields = {
          'streetname': SelectField(
              'streetname',
              coerce=str,
              choices=([street.streetname for street in db.session.query(StreetsMetadata).all()]),
              render_kw={'onchange': "myFunction()"},
              validate_choice=False
              ),
          }
      
      def render(self, template, **kwargs):
          """
          using extra js in render method allow use
          url_for that itself requires an app context
          """
          # solved By Python King
          if 'form' in kwargs and 'streetname' in kwargs['form'] and 'choices' in vars(kwargs['form'].streetname):
              kwargs['form'].streetname.choices = [street.streetname for street in db.session.query(StreetsMetadata).all()]
          self.extra_js = [url_for("static", filename="admin/js/users.js")]
          response = render_miror(self, template, **kwargs)
          return response
      

      【讨论】:

        猜你喜欢
        • 2019-11-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-12
        • 2018-11-02
        • 2010-12-31
        • 1970-01-01
        相关资源
        最近更新 更多