Login

mark a required field by "*" in a template

Author:
brunobord
Posted:
November 20, 2007
Language:
HTML/template
Version:
Not specified
Score:
6 (after 8 ratings)

the trick resides in field.field.required. The intuitive way of testing this in the templates is to access field.required. But it's not the good one. Enjoy!

Found via Django users Google Groups

1
2
3
4
5
6
7
8
9
{% for field in form %}
    <div>
        <label for="{{ field.label }}">{{ field.label_tag }}
        {% if field.field.required %}<span class="special_class">*</span>{% endif %}</label>

        {{ field }}
    </div>

{% endfor %}

More like this

  1. Bootstrap Accordian by Netplay4 5 years, 11 months ago
  2. Bootstrap theme for django-endless-pagination? by se210 8 years, 11 months ago
  3. Bootstrap theme for django-endless-pagination? by se210 8 years, 11 months ago
  4. Reusable form template with generic view by roldandvg 9 years ago
  5. Pagination Django with Boostrap by guilegarcia 9 years, 2 months ago

Comments

dahito (on June 28, 2009):

It should be <label for="{{ field.auto_id }}">

(the id generated in the input,select and texarea fields)

#

dfrankow (on November 1, 2009):

Would be nice to see the snippet for this as a custom template tag

#

davidchambers (on January 19, 2010):

One may instead wrap the label text in a span with class="required", allowing an asterisk to be added via CSS:

span.required:after { content: "*"; }

This provides a useful hook for additional styling as well. For example, one might do the following:

label { color: #666; }
span.required { color: #000; }

This will further differential required from non-required fields.

#

gamesbook (on March 17, 2010):

The code should look more like this:

<div>
    {{ field.errors }}
    <label for="{{ field.auto_id }}">
        {% if field.field.required %}<span class="required">{{ field.label }}</span>
        {% else %}{{ field.label }}{% endif %}
    </label>
    {{ field }}
</div>

Combine with davidchambers styles for effect.

#

Please login first before commenting.