Reputation: 31512
I'm selectively rendering fields on a form.
class SomeForm(forms.Form):
foo = forms.ChoiceField(label='Some Foo', ...)
bar = forms.BooleanField(label='Some Bar', ...)
...
I've got a custom tag that, based on some other logic, lets me iterate over the fields of the form that I need using the FIELD
context variable in the tag:
{% fieldsineed %}
{% if FIELD.field.widget|klass == "CheckboxInput" %}
<li>{{ FIELD }} {{ FIELD.field.label }}</li>
{% else %}
<li>{{ FIELD.label }}: {{ FIELD }}</li>
{% endif %}
{% endfieldsineed %}
(klass
is a filter I got from here which returns the class name of the filtered value.)
Unfortunately, FIELD.label
is only a string. Is there an easy way to render a <label>
tag for a given form field?
Upvotes: 21
Views: 25771
Reputation: 109
You can also do
class SomeForm(forms.Form):
foo = forms.ChoiceField(label='Some Foo', ...)
bar = forms.BooleanField(label='Some Bar', ...)
You can render form like:
<div class="col-12">
<div class="mb-3">
{{ form.foo.label }}
{{ form.foo}}
</div>
</div>
Upvotes: 0
Reputation: 22319
https://docs.djangoproject.com/en/dev/topics/forms/#s-looping-over-the-form-s-fields
Shows you can do
{{ FIELD.label_tag }}
Should render something like
<label for="id_fieldName">Fieldlabel:</label>
Upvotes: 30