我在ModelForm
中有一个views.py
:a_form = MyModelForm(request.POST or None)
我的ModelForm
有很多字段:field1,field2,field3
以及更多
如何在模板中循环访问某些字段(仅说field2
和field3
)?
我尝试过:
#template.html
<label>Example: </label>
{% for text in fields %}
#Hoping to get the a_form.field2 and a_form.field3 checkboxes with "text" as the label
<label>{{text|return_var}}{{text}</label>
{% endfor %}
#views.py
fields = ['field2', 'field3']
return render(request, 'template.html', {'a_form':a_form,"fields":fields)
#forms.py
@register.filter
def return_var(text):
return "a_form." + text
但这只是给我a_form.field2field2
a_form.field3field3
作为页面上的文字,而不是带有我想要标签的复选框。
答案 0 :(得分:0)
您可以使用template.html中的点访问字段:
<form>
{%csrf_token%}
<label for="{{ a_form.field1.id_for_label }}">Your field1:</label>
{{ a_form.field1 }}
....
</form>
阅读Django文档https://docs.djangoproject.com/en/2.0/topics/forms/
中的本节更新:
{% for field in a_form %}
<div class="fieldWrapper">
{{ field.errors }}
{{ field.label_tag }} {{ field }}
{% if field.help_text %}
<p class="help">{{ field.help_text|safe }}</p>
{% endif %}
</div>
{% endfor %}
像这样编辑您的表单:
class MyModelForm(forms.ModelForm):
class Meta:
model = YourModel
fields = ('field1', 'field2', 'field3')
如果您想在模板中包含所有字段,但要隐藏其中的某些字段,则可以使用以下方法隐藏某些字段:
class MyModelForm(forms.ModelForm):
class Meta:
model = YourModel
fields = ('field1', 'field2', 'field3')
widgets = {
'hidden_field4': forms.HiddenInput(),
}
然后,您可以遍历您的隐藏字段或/和可见字段:
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{# Include the visible fields #}
{% for field in form.visible_fields %}
<div class="fieldWrapper">
{{ field.errors }}
{{ field.label_tag }} {{ field }}
</div>
{% endfor %}
最终
要按照评论中的说明将文件分组,可以执行以下操作:
class MyModelForm(forms.ModelForm):
class Meta:
model = YourModel
def field2to8(self):
return [field for field in self if not field.is_hidden
and field.name in ('field2', ..., 'field8')]
def field8to20(self):
return [field for field in self if not field.is_hidden
and field.name in ('field8', ..., 'field20')]
然后在此模板中添加
{% for field in form.field2to8 %}
{{ field.label_tag }} {{ field }}
<span class="help-block">{{ field.help_text }}</span>
{% endfor %}
{% for field in form.field8to20 %}
{{ field.label_tag }} {{ field }}
<span class="help-block">{{ field.help_text }}</span>
{%endfor%}