Python Django中同一行上的多个字段

Python Django中同一行上的多个字段,python,django,django-forms,Python,Django,Django Forms,我想为数据库中的每个项目显示一个带有标签、文本字段和复选框的行。除了新行上的复选框外,我已经成功地做到了这一点。我不想: <tr> <td>Label</td> <td>Input</td> <td>Checkbox</td> <tr> 视图.py class AttributeForm(forms.Form): def __init__(self, *args,

我想为数据库中的每个项目显示一个带有标签、文本字段和复选框的行。除了新行上的复选框外,我已经成功地做到了这一点。我不想:

<tr>
    <td>Label</td>
    <td>Input</td>
    <td>Checkbox</td>
<tr>
视图.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)
attribute_form = AttributeForm(extra=user)
return render_to_response('user.html', {'username': username, 'attribute_form': attribute_form})
模板(user.html)


{{attribute_form.as_table}}

编辑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>

属性_form%}中字段的{%
{%cycle''''%}{%cycle field.label_标记''%}{%cycle''''%}
{{field}}{{attribute_form.field.errors}
{%if不是forloop.last%}{%cycle'''%}{%endif%}
{%endfor%}

。as_table
在单独的表行中呈现每个表单字段。您应该。

您是如何生成此代码的?显示使用实际模板或表单代码。这是给管理员的还是给自定义应用的?你能给我们看看Django用于此的模板吗?是的,这是可能的,但非常难看,因为我正在生成表单中的字段,我不知道我有多少个字段或它们的名称,所以我必须使用相同的结构在视图中生成字段。如果有另一种更好、更模块化的方法,我可以用另一种方法做什么?您希望Django(或其他一些工具)知道任何名为“delete_u%s”的字段都应该与字段“%s”分组,并使用一个简单的方法神奇地呈现它们,对吗?也许我不完全理解文档,但在我看来,我需要硬编码tr和td中每个字段的名称,就像我要完全用HTML创建表一样,这使得Django表单的使用变得毫无用处?@olofom您不需要对名称进行硬编码。只需将文档稍微滚动到::-)啊,是的,好吧,你是对的,它最终奏效了。如果有人想知道我的模板在我的帖子中的最终结果是像EDIT2一样。
<form action="" method="post">
    <table>{{ attribute_form.as_table }}</table>
    <input type="submit" value="Save attributes">
</form>
    <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>