SelectField renders unicode syntax

时间:2015-05-08 09:52:05

标签: forms unicode flask-wtforms

When dynamically creating choices for SelectField in WTForms, I get (u'Choice',) rendered in the dropdown list. I suspect its something to do with unicode, but no idea how to get the correct string.

for example

form.group_id_name.choices = [(row, row) for row in db.session.query(entry.group_id_name).distinct()]

In my forms I have

 group_id_name = SelectField('group_id_name')

I would like it to render

<select id="group_id_name" name="group_id_name"><option value="Choice1">Choice1</option><option value="Choice2">Choice2</option></select>

Instead I get

<select id="group_id_name" name="group_id_name"><option value="(u'Choice1',)">(u'Choice1',)</option><option value="(u'Choice2',)">(u'Choice2',)</option></select>

1 个答案:

答案 0 :(得分:0)

这与Unicode没有任何关系。

query()返回每行的列值序列。对于只包含一列的查询,您将得到一个长度为1的元组。

当您将元组隐式转换为字符串作为模板的一部分时,您将获得元组的Python代码表示,其类似于(somevalue,)

您希望在模板中包含列本身的字符串值,因此您应该访问序列的第一个元素,例如:

form.group_id_name.choices = [(row[0], row[0]) for row in db.session.query(entry.group_id_name).distinct()]

或使用解包指定:

form.group_id_name.choices = [(name, name) for (name,) in db.session.query(entry.group_id_name).distinct()]