How to render form field with information that it is required How to render form field with information that it is required django django

How to render form field with information that it is required


As of Django 1.2, if your form has an attribute named required_css_class, it will be added to BoundField.css_classes for required fields. You can then use CSS to style the required parts of the form as desired. A typical use case:

# views.pyclass MyForm(django.forms.Form):    required_css_class = 'required'    …

/* CSS */th.required { font-weight: bold; }

<!-- HTML --><tr>  <th class="{{form.name.css_classes}}">{{form.name.label_tag}}</th>  <td>{{form.name.errors}}{{form.name}}</td></tr>

If you use Form.as_table(), Form.as_ul, and Form.as_p, they do this automatically, adding the class to <tr>, <li>, and <p>, respectively.


You also can use a field.field.required property:

{% for field in form %}  {{field.label}} {% if field.field.required %} * {% endif %}  {{field}}  {{field.errors}}{% endfor %}


The best way for such purposes I have found is to render form's output via an html template. How to do this is described here. By luck, the example puts an asterisk after required fields just like you want.