views:

429

answers:

2

Hi,

When overwriting a form clean method how do you know if its failed validation on any of the fields? e.g. in the form below if I overwrite the clean method how do I know if the form has failed validation on any of the fields?

class PersonForm(forms.Form):
    title = Forms.CharField(max_length=100)
    first_name = Forms.CharField(max_length=100)
    surname = Forms.CharField(max_length=100)
    password = Forms.CharField(max_length=100)

def clean(self, value):
    cleaned_data = self.cleaned_data

    IF THE FORM HAS FAILED VALIDATION:
        self.data['password'] = 'abc'
        raise forms.ValidationError("You have failed validation!")
    ELSE:
        return cleaned_data 

Thanks

+1  A: 

If your data does not validate, your Form instance will not have a cleaned_data attribute

Django Doc on Accessing "clean" data

Use self.is_valid().

stefanw
so would i just do a check on cleaned_datae.g.if not self.cleaned_data: #do something
John
No, the attribute doesn't exist, you would get an AttributeError. I extended my answer.
stefanw
+1  A: 

You can check if any errors have been added to the error dict:

def clean(self, value):
    cleaned_data = self.cleaned_data

    if self._errors:
        self.data['password'] = 'abc'
        raise forms.ValidationError("You have failed validation!")
    else:
        return cleaned_data 

BONUS! You can check for errors on specific fields:

def clean(self, value):
    cleaned_data = self.cleaned_data

    if self._errors and 'title' in self._errors:
        raise forms.ValidationError("You call that a title?!")
    else:
        return cleaned_data 
Mark Lavin