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.
To display the form errors, you use form. is_valid() to make sure that it passes validation. Django says the following for custom validations: Note that any errors raised by your Form.
Probably the most common method is to display the error at the top of the form. To create such an error, you can raise a ValidationError from the clean() method. For example: from django import forms from django.
The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.
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'
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
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With