0

我有一个从 sqlite3 数据库获得的元组列表。我试图以不同的方式获取数据库,但没有任何运气,这不是这个问题的人,但最终如果它有助于格式化我的单选按钮表单的描述,我会欣喜若狂。

我的清单如下:

images = [(1, u'True', u'file_Name.img', u'img', u'train', u'2013-02-0509:59:46.442660file.ext',
   u' file2.ext', u'ABC', u"[u'prod_one-prod_two']", u'name@email.com',
   u'nothing happens', u'2013-02-0509:59:46.442660', u"[u'ftp://link/file_Name.img', 
   u'ftp://link/file3.ext', u'ftp://link/file_Name.log']"),(2, u'True',u'file_Name.img', 
   u'img', u'train', u'2013-02-0509:59:46.442660file.ext', u' file2.ext', u'ABC', 
   u"[u'prod_one-prod_two']", u'name@email.com', u'nothing happens', 
   u'2013-02-0509:59:46.442660', u"[u'ftp://link/file_Name.img', 'ftp://link/file3.ext', 
   u'ftp://link/file_Name.log']")]

我想做的是让选择的值成为每个元组的第一个元素

rows = [(str(x[0]), x) for x in images]
form.images.choices = rows

然而,它看起来好像我只是用 unicode 字符和所有东西打印了那个乱七八糟的东西。

所以我试图在一个漂亮的表格中格式化它,以便很容易看到每个元组包含的内容

descriptionList = []
description = ''
for i in images:
    for j in i:
        description = description + '\t|' + str(j)
    descriptionList.append(description)


rows = [(str(x[0]), y) for x, y in zip(images, descriptionList)]
form.images.choices = rows

但是,当我显示表单时,它在输出中没有制表符。

所以现在我正在考虑将 descriptionList 传递到模板中并将其显示在每个单选框旁边以充当表单中的描述。

return render_template('database.html', form=form, descriptions = descriptionList)
{% for subfield, desc in zip(form.images, descriptions) %}
        <tr>
            <td>{{ subfield }}</td>
            {# {{ subfield.label }} (this is a comment)#}
            desc <br>
        </tr>
    {% endfor %}

但是我收到错误“UndefinedError:'zip'未定义”

没有它我得到:

{% for subfield, desc in (form.images, descriptions) %}
ValueError: too many values to unpack

关于如何解决这个问题的任何建议都令人惊叹。谢谢

4

2 回答 2

1

让我从一个更简单的图像列表开始,作为一个更简洁的示例:

images = [
            (1, u'True', u'file_one.jpg', u'2013'),
            (2, u'False', u'file_two.jpg', u'2012'),
]

然后,您将该元组列表细化为用于表单值的选择,本质上目标是为 wtforms 提供两个值元组的列表:

[
    (1,'file_one.jpg'), 
    (2,'file_two.jpg')
]

但是你使用这个列表理解:

rows = [(str(x[0]), x) for x in images]
form.images.choices = rows

这将产生:

[
    (1, (1, u'True', u'file_one.jpg', u'2013')), 
    (2, (2, u'False', u'file_two.jpg', u'2012'))
]

这对 wtforms 没有用,它不知道如何处理元组中的元组。因此,您需要选择标签的值,或者更好地格式化该数据。

所以要么改变你的列表理解来选择一个更好的描述,这将使你达到目标:

rows = [(x[0],x[2]) for x in images]

或者将所有数据连接在一起以提供更详细但可能对您有用的描述:

rows = [(x[0], "\t|".join([str(y) for y in x])) for x in images]

这将导致:

[
    (1, '1\t|True\t|file_one.jpg\t|2013'), 
    (2, '2\t|False\t|file_two.jpg\t|2012')
]

阅读更多关于列表推导的内容。

于 2013-02-06T17:37:29.120 回答
0

尝试不在 html 模板中准备 zip(form.images, descriptions),而是在 python 代码中,然后将其发送到模板:

   imgs_with_descriptions = zip(form.images, descriptionList)

在模板中:

   {% for subfield, desc in imgs_with_descriptions %}
       <tr>
            <td>{{ subfield }}</td>
            {# {{ subfield.label }} (this is a comment)#}
            desc <br>
        </tr>
   {% endfor %}
于 2013-02-06T16:16:26.437 回答