I am attempting to validate a form (and it used to work before). For some reason, I can\'t seem to get the various cleaning functions such as clean_username(self) to get called
I discovered the source of the error after diving into the Django forms.py source.
It seems that if a field is left blank, the form raises a ValidationError for that field after calling field.clean()
, but it then does not call clean_<fieldname>
, but it still calls the main clean method of the class. In order to deal with a clean method that uses those blank fields you have to do the following:
def clean(self):
try:
password = self.cleaned_data['password']
# etc
except KeyError:
raise ValidationError('The password field was blank.')
return self.cleaned_data
You can override this by using required=False
in your field constructors.
username = forms.CharField(max_length=30, required=False)
password = forms.CharField(max_length=30,widget=forms.PasswordInput, required=False)
This seems illogical for your example, but can be useful if other instances