当使用 Django 管理表单创建新对象或修改现有对象时,<label>
必填模型字段的标签使用类属性 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>
但是,使用 Django ModelForm 时情况并非如此。模板文件中由以下代码段生成的 HTML 代码
<table>
{{ toolForm.as_table }}
</table>
<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>
任何想法如何以有效的方式标记必填字段的标签?
最佳答案
遵循 Ralf 对 xj9 描述的类似问题的提示 here ,下面的解决方案对我来说很好:
<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>
相应的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: " *";
}
关于css - 使用 Django ModelForm 时标记必填字段的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51369757/