Reputation: 163
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?
Upvotes: 5
Views: 3194
Reputation: 163
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: " *";
}
Upvotes: 7