Reputation: 71
why comes a keyerror instead of a validation error when one field is empty? The fields should be required=True
by default
class form(forms.ModelForm):
adminAccount = forms.CharField()
adminPassword = forms.CharField(widget=forms.PasswordInput)
def userCheck(self, user, password):
# do something
def clean(self):
self.userCheck(self.cleaned_data['adminAccount'],
self.cleaned_data['adminPassword'])
Upvotes: 1
Views: 1469
Reputation: 900
It is your code that is raising the KeyError
here:
self.userCheck(self.cleaned_data['adminAccount'],
self.cleaned_data['adminPassword'])
Because you're trying to access self.cleaned_data[field]
when field was not posted.
The documentation provides an example that explains how to validate data that depends on more than one field. According to the examples you should do something like:
cleaned_data = super(form, self).clean()
adminAccount = cleaned_data.get('adminAccount')
adminPassword = cleaned_data.get('adminPassword')
if adminAccount and adminPassword:
# proceed with your validation
return cleaned_data
Also, remember that Form.clean()
must return the cleaned_data dict.
Upvotes: 1