[英]How do I add a red asterisk to form fields that fail to validate?
If a form field fails to validate, Django will display a helpful message (eg "This field is required").如果表单字段无法验证,Django 将显示有用的消息(例如“此字段是必需的”)。 However, in addition to the helpful message, I also want to display a red asterisk next to the form field itself if there are any validation errors for the field.但是,除了有用的消息之外,如果该字段存在任何验证错误,我还想在表单字段本身旁边显示一个红色星号。 Something like:就像是:
Excerpt from my template:摘自我的模板:
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit"/>
</form>
I know I can insert the asterisk using manual form rendering , but I am looking for a way to do this without editing the template.我知道我可以使用手动表单渲染插入星号,但我正在寻找一种无需编辑模板的方法。 Is there a way to do this?有没有办法做到这一点? Perhaps it can be done by overriding specific django.forms.Form
methods?也许可以通过覆盖特定的django.forms.Form
方法来完成?
You can add error_css_class
attribute to the Form
and when a field has an error, this attribute's value will be added to the field's wrapper html classes ( p
in this case).您可以向Form
添加error_css_class
属性,当字段出现错误时,该属性的值将添加到该字段的包装 html 类(在本例中为p
)。
Then in your css you can add a rule like:然后在您的 css 中,您可以添加如下规则:
.error_css_class input::after {
content: "*";
color: red;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.