[Answer]-How to add own class into field if this field is not valid?

1👍

Edited to answer more precisely.

If you want to specify a class for error or required fields:

class MyForm(Form):
    error_css_class = 'error' #here you can set this to 'invalid'
    required_css_class = 'required'

ref: https://docs.djangoproject.com/en/1.6/ref/forms/api/

You can also change your class for one field with:

myfield= forms.CharField(attrs={'class': 'myclass'})

ref: https://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.Widget.attrs

0👍

In your forms clean method you could update the attrs of the widgets for all fields that error to achieve something similar to what you want.

from django import forms

class MyForm(forms.Form):
    myfield = forms.CharField()

    def clean(self):
        if 'myfield' in self._errors:
            self.fields['myfield'].widget.attrs.update({'class': 'invalid'})

        # Or to add the class to the input of all erroring fields:
        for field in self.fields:
            if field in self._errors:
                self.fields[field].widget.attrs.update({'class': 'invalid'})

        return super(MyForm, self).clean()

Leave a comment