简体   繁体   English

如何在表单验证失败的字段中添加红色星号?

[英]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.

相关问题 如何在django中添加一个红色星号来显示表单中的必填字段? - How do I put a a red asterisk to show a required field in a form in django? 尝试验证数据时如何在表单中添加多个字段? - How do add multiple fields to a Form when trying to validate data? 如何在我的 django-login 视图中添加红色星号 (*)? - How can i add a red asterisk (*) in my django-login view? 如何在 Django 表单上填写 label 字段? - How do I label fields on a Django form? 如何在表单的标识字段上验证表单上的字段。 Django的 - How I can validate fields on forms on identity fields in form. Django Django:如何将任意 html 属性添加到表单上的输入字段? - Django: How do I add arbitrary html attributes to input fields on a form? 如何在 Django 中验证纯 HTML 表单字段 - How to validate plain HTML form fields in django 如何验证表单并显示填充字段的值? - how validate form and show the value of the filled fields? g-如何将额外的表单字段(不是来自页面模型)添加到管理页面编辑表单并获取and渲染 - Wagtail - how do I add extra form fields (not from page model) to admin page edit form and get wagtail rendering django-filters:如何使用 ModelChoiceFilter,无法将类添加到表单字段并且无法设置表单标签 - django-filters: How do I use ModelChoiceFilter, unable to add classes to form fields and unable to set form labels
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM