WTForms 将选项转换为字符串

WTForms turns choices into strings

我正在尝试从 SQLAlchemy 数据库动态创建 WTForm SelectField 条目,如图所示 但它似乎在每个选择元组的第一部分 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()])

来自 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 的情况下更新用户模型,则一种更适合未来的方法可以将正确的对象强制返回给用户字符串被正确修改,但 'id' 将始终作为主键可用。