WTForms将选择变成字符串

时间:2018-04-09 11:49:50

标签: flask wtforms flask-wtforms

我正在尝试从SQLAlchemy数据库中动态创建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()])

1 个答案:

答案 0 :(得分:1)

来自wtforms docs:

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.
"""

因此,如果在没有正确修改 repr 字符串的情况下更新用户模型,那么使用user.id的传统方法是一种更加面向未来的方法,可以将正确的对象强制保留回用户。 #39; ID'将始终作为主键提供。