简体   繁体   中英

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"). 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?

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).

Then in your css you can add a rule like:

.error_css_class input::after {
    content: "*";
    color: red;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM