4

When using the Django admin forms to create a new or modify an existing object, the <label> tags of mandatory model fields are declared with class attribute required, e.g.

<div>
  <label class="required" for="id_title">Title:</label>
  <input class="vTextField" id="id_title" maxlength="255" name="title" type="text" required />
  <p class="help">A title for this tool</p>
</div>

However, this is not the case when using Django ModelForm. The HTML code produced by the following piece of code in a template file

<table>
{{ toolForm.as_table }}
</table>

comes without any class attributes for the <label> tag that would help to style appropriately labels of fields which are required:

<table>
<tr>
<th>
  <label for="id_title">Title:</label>
</th>
<td>
  <input id="id_title" maxlength="255" name="title" type="text" required />
  <br /><span class="helptext">A title for this tool</span>
</td>
</tr>
</table>

Any ideas how to mark the label of mandatory fields in an efficient way?

gkaravo
  • 133
  • 1
  • 8
  • 1
    See also [this](https://stackoverflow.com/questions/6959178/how-to-set-css-class-of-a-label-in-a-django-form-declaration) similar question for ideas – Ralf Jul 16 '18 at 20:48

1 Answers1

6

Following Ralf's hint for a similar problem as described by xj9 here, the solution below works fine for me:

<table>
{% for field in toolForm %}
  <tr>
    <th>
        <label class="field-label{% if field.field.required %} field-required{% endif %}" for="{{ field.name }}">{{ field.label }}</label>
    </th>
    <td>
        {% if field.errors %}<span class="field-error">{{ field.errors }}</span>{% endif %}
        {{ field }}<br/>
        {% if field.help_text %}<span class="field-helptext">{{ field.help_text|safe }}</span>{% endif %}
    </td>
  </tr>
{% endfor %}
</table>

The corresponding CSS which also adds a '*' sign next to the field names that are required could be the following:

.field-label {
    font-weight: normal;
}
.field-helptext {
    font-size: 12px;
}
.field-error {
    font-size: 14px;
    color: red;
}
.field-required {
    font-weight: bold;
}
.field-required:after {
    content: " *";
}
gkaravo
  • 133
  • 1
  • 8