6

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?

1
  • 2
    See also this similar question for ideas Commented Jul 16, 2018 at 20:48

2 Answers 2

7

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: " *";
}
Sign up to request clarification or add additional context in comments.

Comments

0

The Form.required_css_class is applied to the labels of required fields if you set it to a string rather than the default None.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.