【问题标题】:SQLAlchemy/WTForms: set default selected value for QuerySelectFieldSQLAlchemy/WTForms:为 QuerySelectField 设置默认选定值
【发布时间】:2014-03-02 00:13:30
【问题描述】:

这个[示例][1] 在 Flask 中使用 WTForms 和 SQLAlchemy 设置表单,并将 QuerySelectField 添加到表单中。我没有使用flask.ext.sqlalchemy,我的代码:

ContentForm = model_form(Content, base_class=Form)
ContentForm.author = QuerySelectField('Author', get_label="name")
myform = ContentForm(request.form, content)
myform.author.query = query_get_all(Authors)

现在我想设置 QuerySelectField 的选择列表的默认值

尝试在 QuerySelectField 中传递 default kwarg 并设置 selected 属性。没有任何效果。我错过了什么明显的东西吗?有人可以帮忙吗?

【问题讨论】:

    标签: python sqlalchemy flask selection wtforms


    【解决方案1】:

    您需要将 default 关键字参数设置为您希望成为默认值的 Authors 实例:

    # Hypothetically, let's say that the current user makes the most sense
    # This is just an example, for the sake of the thing
    user = Authors.get(current_user.id)
    ContentForm.author = QuerySelectField('Author', get_label='name', default=user)
    

    或者,您可以在实例化时将实例提供给字段:

    # The author keyword will only be checked if
    # author is not in request.form or content
    myform = ContentForm(request.form, obj=content, author=user)
    

    【讨论】:

    • 第一种方法没有效果。第二个导致TypeError: 'ContentForm' object is not callable 异常...
    • @casual - 抱歉,第二个应该是 myform 的实例化 - 已更新。 (至于第一个,如果你使用作者的id 会发生什么......我不认为它应该工作,查看代码,但尝试不会有什么坏处它)
    • 很奇怪,选择框默认正确的唯一情况是myform = ContentForm(request.form, author=user) 但是当然所有其他表单字段都是空的。这可能是 Flask 请求的问题吗?
    • @casual - 我漏掉了应该用于contentobj= - 我们需要做的是签入request.form,如果那里没有内容,请填写带有来自obj 的数据的表单(在本例中为content,如果content 没有author,则使用我们通过关键字参数提供的author。我已经更新了我的第二个示例,它 应该现在可以工作了。
    • 我的代码中的其他地方有一个错误。你的答案有效。
    【解决方案2】:

    试试这个:

    ContentForm.author = QuerySelectField(
        'Author', 
        get_label="name", 
        default=lambda: Authors.get(current_user.id).one()
    )
    

    【讨论】:

      猜你喜欢
      • 2013-08-21
      • 1970-01-01
      • 2020-02-21
      • 1970-01-01
      • 2012-08-19
      • 1970-01-01
      • 2020-12-14
      • 1970-01-01
      • 2022-12-04
      相关资源
      最近更新 更多