Login

mark a required field by "*" in a template

Author:
brunobord
Posted:
November 20, 2007
Language:
HTML/template
Version:
Not specified
Tags:
newforms forms templates field required
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. User groups template tag with "else" block support (Allow checking several groups) by br0th3r 2 years, 10 months ago
  2. User group template tag with "else" block support by GomoX 7 years, 6 months ago
  3. User or Group entry field & widget by Scanner 7 years, 10 months ago
  4. User group template tag by jdriscoll 7 years, 8 months ago
  5. More information about users and groups in user admin by ramusus 5 years, 7 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.