I am using Django's modelform and its really good. How can I highlight the actual text box (e.g. border:red ) if there is a validation error associated with it. Basically what i want is to add a class (error) if there is a validation error to a field.
Asked
Active
Viewed 2.1k times
20

aaronasterling
- 68,820
- 20
- 127
- 125

Myth
- 1,562
- 5
- 15
- 25
-
How are you generating the form html in template? Printing the whole form object at once or printing field by field? – Imran Jan 31 '11 at 06:42
-
I am looping through form elements and printing errors, field and label separately. – Myth Jan 31 '11 at 07:24
5 Answers
18
What about defining error_css_class? http://docs.djangoproject.com/en/dev/ref/forms/api/#styling-required-or-erroneous-form-rows?
class MyForm(ModelForm):
error_css_class = 'error'

errx
- 1,761
- 4
- 18
- 25
-
9This gives class to container of the form field. What if I want to assign class to form field itself? – Myth Feb 02 '11 at 04:44
-
1
-
2
10
To answer the original question.
You can add the desired class to the field in the view to where you are submitting your form and doing your form.is_valid()
check. Not the prettiest but it will work.
def submit_form(request):
if request.method = 'POST':
if. form.is_valid():
# Do something with clean form data
pass
else:
# Append css class to every field that contains errors.
for field in form.errors:
form[field].field.widget.attrs['class'] += ' my-css-class'
return render(request, submit_form.html, {
'form': form
})

holmberd
- 2,393
- 26
- 30
-
1Or to encapsulate this process you can override form.is_invalid() and put this `for field in form.errors:` loop in it – Am Ben Oct 09 '22 at 21:47
3
Expanding upon errx's answer.
Add the CSS
.error input, .error select {
border: 2px red solid;
}
to specifically highlight the field

Augier
- 311
- 2
- 13
1
template :
<div style="color:red">{{ userForm.short_description.errors.as_text }}</div>

Mohd Ahshan Danish
- 125
- 1
- 8