2
Have a look at Form and field validation in the official docs in the Cleaning and validating fields that depend on each other section.
As Rohan commented you should clean fields that depend on each other in the clean() method.
When clean_email is called external_reference hasn’t been cleaned yet and there for it isn’t in self.cleaned_data yet (hence the KeyError).
def clean(self):
cleaned_data = super(Class, self.clean)
email = cleaned_data.get('email')
external_reference = cleaned_data.get('external_reference')
if email and external_reference:
if User.objects.filter(email=email).exists():
try:
#User exists, use form to update user
Profile.objects.get(external_reference=external_reference, user__email=email)
except Profile.DoesNotExist:
self.add_error('email', 'Email in use')
return cleaned_data
Remember to use get on cleaned_data to get email and external_reference and check if they exist because if their individual clean_field methods raised validation errors then they would not be in cleaned_data and you would get a KeyError once again.
PS: If you are on django version prior to 1.7 use self._errors[’email’] = self.error_class([‘Email in use’]) instead of self.add_error.
Source:stackexchange.com