【问题标题】:WTForms turns choices into stringsWTForms 将选择转换为字符串
【发布时间】:2018-04-09 11:49:50
【问题描述】:

我正在尝试从 SQLAlchemy DB 动态创建 WTForm SelectField 条目,如 here 所示,但它似乎在每个选择元组的第一部分执行 repr()str(),这应该是 User 对象.我刚刚发现 QuerySelectFieldwtforms.ext.* 软件包已被弃用。

class ChangeAccountForm(FlaskForm):
    def __init__(self, *args, **kwargs):
        # Queries user database and sets user choices
        super(ChangeAccountForm, self).__init__(*args, **kwargs)
        self.user.choices = [(i, i.username) for i in User.query.all()]

    user = SelectField('Gebruiker', validators=[Optional()])

【问题讨论】:

  • 是否有理由需要在渲染模板中使用整个 User 对象?通常,您可以使用 user.id(如您链接的答案)字段并在表单发布后使用该值查询您的数据库。
  • @Maarten 不是真的,它只是更优雅。

标签: flask wtforms flask-wtforms


【解决方案1】:

来自 wtforms 文档:

class wtforms.fields.SelectField(default field arguments, choices=[], 
    coerce=unicode, option_widget=None)

"""        
Select fields keep a choices property which is a sequence of (value, 
label) pairs. The value portion can be any type in theory, but as form 
data is sent by the browser as strings, you will need to provide a 
function which can coerce the string representation back to a 
comparable object.
"""

因此,使用 user.id 的传统方法是,如果在未正确修改 repr 字符串的情况下更新 User 模型,则可以将正确的对象强制返回给用户,但 ' id' 将始终可用作主键。

【讨论】:

    猜你喜欢
    • 2012-09-08
    • 2017-12-15
    • 1970-01-01
    • 2019-09-15
    • 2016-08-11
    • 1970-01-01
    • 2021-07-19
    • 2019-10-10
    • 2014-02-15
    相关资源
    最近更新 更多