Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding css class to field on validation error in django

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.

like image 777
Myth Avatar asked Jan 31 '11 05:01

Myth


People also ask

How do I display validation error in Django?

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.

How do I extend a validation error in Django?

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.

How do I validate fields in 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.


2 Answers

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'
like image 176
errx Avatar answered Sep 20 '22 01:09

errx


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
    })
like image 40
holmberd Avatar answered Sep 21 '22 01:09

holmberd