Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Render the <label> of a single form field

Tags:

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?

like image 916
a paid nerd Avatar asked Jun 01 '11 23:06

a paid nerd


1 Answers

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>
like image 135
James Khoury Avatar answered Oct 22 '22 09:10

James Khoury