使用 Django ModelForm 时标记必填字段的标签

gka*_*avo 2 css django django-templates django-models django-forms

使用 Django 管理表单创建新对象或修改现有对象时,<label>必须使用 class 属性声明模型字段的标签required,例如

<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>
Run Code Online (Sandbox Code Playgroud)

但是,使用 Django ModelForm 时情况并非如此。模板文件中由以下代码段生成的 HTML 代码

<table>
{{ toolForm.as_table }}
</table>
Run Code Online (Sandbox Code Playgroud)

<label>标签没有任何类属性,这有助于为所需的字段设置适当的标签样式:

<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>
Run Code Online (Sandbox Code Playgroud)

任何想法如何以有效的方式标记必填字段的标签?

gka*_*avo 5

按照 Ralf 对 xj9此处描述的类似问题的提示,下面的解决方案对我来说很好用:

<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>
Run Code Online (Sandbox Code Playgroud)

相应的 CSS 还在'*'所需的字段名称旁边添加了一个符号,可能如下所示:

.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: " *";
}
Run Code Online (Sandbox Code Playgroud)