20

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?

Community
  • 1
  • 1
a paid nerd
  • 30,702
  • 30
  • 134
  • 179

2 Answers2

29

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>
Saransh Singh
  • 730
  • 4
  • 11
James Khoury
  • 21,330
  • 4
  • 34
  • 65
  • 2
    I _did_ spend a good twenty minutes reading docs and digging around on the shell with `dir()`. It's easy to miss. DBAD – a paid nerd Jun 02 '11 at 00:10
  • how to get it without the `:`? Edit: Sorry, reading helps. The forms `label_suffix` will help you... – benzkji Mar 03 '20 at 12:53
  • Thanks a lot. I've been looking for this for over a day now. Do you also know how to access the `id` attribute of the `label_tag`? – KareemJ Apr 04 '20 at 13:35
  • 1
    @KareemJeiroudi on https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.BoundField.label_tag The label_tag method takes an attrs dictionary. I think this might work. I recommend you ask this as a separate question to get a complete answer. – James Khoury May 03 '20 at 23:07
0

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>