mark a required field by "*" in a template

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. Rendering a form by looping through its fields in a template by simon 4 years, 9 months ago
  2. Error rate limiter by s29 2 years, 7 months ago
  3. Run model validation before saving a model instance by buriy 2 years, 5 months ago
  4. South introspection rules for TimeZoneFields by serkan 2 years, 3 months ago
  5. CSRF this! by oggy 4 years, 8 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.

#

(Forgotten your password?)