【问题标题】:Multiple fields on the same row in DjangoDjango中同一行上的多个字段
【发布时间】:2012-03-29 07:31:43
【问题描述】:

我想为数据库中的每个项目显示一行,其中包含一个标签、一个文本字段和一个复选框。除了新行上的复选框外,我已经设法做到了。我不想:

<tr>
    <td>Label</td>
    <td>Input</td>
    <td>Checkbox</td>
<tr>

但我得到的只是:

<tr>
    <td>Label</td>
    <td>Input</td>
</tr>
<tr>
    <td>Checkbox</td>
</tr>

有人知道怎么做吗?

编辑:

要生成我做的表格:

forms.py

class AttributeForm(forms.Form):  
    def __init__(self, *args, **kwargs):
        extra = kwargs.pop('extra')
        super(AttributeForm, self).__init__(*args, **kwargs)

        for key in extra:
            self.fields[key] = forms.CharField(label=key, initial=extra[key], required=False)
            self.fields['delete_'+key] = forms.BooleanField(label='', required=False)

views.py

attribute_form = AttributeForm(extra=user)
return render_to_response('user.html', {'username': username, 'attribute_form': attribute_form})

模板(user.html)

<form action="" method="post">
    <table>{{ attribute_form.as_table }}</table>
    <input type="submit" value="Save attributes">
</form>

编辑 2:

我的模板最终是这样的:

    <form action="" method="post">
        <table>
            <tr>
                {% for field in attribute_form %}
                    {% cycle '<th>' '' %}{% cycle field.label_tag '' %}{% cycle '</th>' '' %}
                    <td>{{ field }}{{ attribute_form.field.errors }}</td>
                    {% if not forloop.last %}{% cycle '' '</tr><tr>' %}{% endif %}
                {% endfor %}
            </tr>
        </table>
        <input type="submit" value="Save attributes">
    </form>

【问题讨论】:

  • 你是如何生成这段代码的?显示使用实际的模板或表单代码。这是针对管理员还是针对自定义应用程序?
  • 你能给我们看看 Django 使用的模板吗?

标签: python django django-forms


【解决方案1】:

.as_table 在单独的表格行中呈现每个表单字段。你应该render the form manually

【讨论】:

  • 是的,这是可能的,但非常难看,因为我正在生成表单中的字段,我不知道我有多少字段或它们被称为什么,所以我必须使用相同的结构以在视图中生成字段。如果有另一种更好、更模块化的方法。
  • @olofom 另一种方法是什么?您希望 Django(或其他工具)知道名称为“delete_%s”的任何字段都应与字段“%s”分组,并使用一种简单的方法神奇地呈现它们,对吧?
  • 也许我不完全理解文档,但正如我所见,我需要硬编码 tr 和 td 中每个字段的名称,就像我打算完全用 HTML 创建表一样,这那么使用 Django 表单就没有用了吗?
  • @olofom 您不需要对名称进行硬编码。只需将文档稍微滚动到this。 :-)
  • 啊,是的,好的,你是对的,它最终奏效了。如果其他人想知道我的模板最终像我的帖子中的 EDIT2 一样。
猜你喜欢
  • 2011-08-16
  • 2019-02-22
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-20
  • 1970-01-01
相关资源
最近更新 更多