【发布时间】:2021-01-31 15:29:48
【问题描述】:
我有一个内联表单集,其中包含清晰的表单。它工作得很好,但我得到每行上方显示的标签。我更喜欢它们一次,在字段表的顶部,但不太确定如何实现这一点。
我定义了一个布局对象,我试图关闭标签以开始,但我猜辅助对象不能以这种方式工作......
class Formset(LayoutObject):
template = "missions/formset.html"
def __init__(self, formset_name_in_context, template=None):
self.formset_name_in_context = formset_name_in_context
self.fields = []
if template:
self.template = template
self.helper = FormHelper()
self.helper.form_show_labels = False
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK):
formset = context[self.formset_name_in_context]
return render_to_string(self.template, {"formset": formset})class Formset(LayoutObject):
template = "missions/formset.html"
在主窗体中使用如下:
self.helper.layout = Layout(
< snipped the main form parts as not relevant to the question >
Div(
Fieldset(
_("Invitees"),
Field("allow_invitees_to_add_others", css_class="col-md-12"),
Formset("invitees"),
),
),
)
)
在我的 formset.html 中
<table>
{{ formset.management_form|crispy }}
{% for form in formset.forms %}
<tr class="{% cycle 'row1' 'row2' %} formset_row-{{ formset.prefix }}">
{% for field in form.visible_fields %}
<td>
{# Include the hidden fields in the form #}
{% if forloop.first %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% endif %}
{{ field.errors.as_ul }}
{{ field|as_crispy_field }}
</td>
{% endfor %}
</tr>
{% endfor %}
</table>
所以我想知道:
- 如何关闭表单集中每一行的标签。
- 然后如何在
{% for %}循环之前循环遍历模板中的标签,这样我只需显示一次。
编辑: 好的,所以我已经处理了将顶部标题放入,但仍然不知道如何关闭表单集中每个表单的标题...
{% if forloop.first %}
<thead>
<tr>
{% for field in form.visible_fields %}
<th scope="col">
{{ field.label }}
</th>
{% endfor %}
</tr>
</thead>
{% endif %}
【问题讨论】:
标签: django django-forms django-templates django-crispy-forms