Accessing `widget` attribute within validators.

I have some example pseudo code for a form here:

class ExampleForm(forms.Form):

    field_1 = forms.FloatField(
        label = "Field 1",
        widget = forms.NumberInput(attrs = {
            "class": "form-control" # This is just a bootstrap class.
        validators = [] # Some lambda function to a validator. 

I populate the validators with a lambda function that validates the form input.
What I would like to know is, Is there a way I can access the widget property of the field in the validator function ? What my main goal is if the validation fails, I can add an is-invalid class (again a bootstrap class) to the widget.attrs to show which inputs have failed.

I can of course do this inside each fields clean_ method django provides but in case of a lot of fields, that just reeks of DRY violation.

Any help would be appreciated ! :slightly_smiling_face:
Have a good day !

You can do it within the clean() method (the global clean, not the per-field clean) by iterating over the ValidationErrors and adjusting the fields accordingly.

Could you provide a sample example ? I have looked in Form and field validation | Django documentation | Django but I don’t seem to find anything similar.

See the docs in the Forms API page for Form.errors along with the .as_data method.

Thanks for the help. Got it. The fields are available in self.error.items() and I can use that.