I have a user registration form that has a “password” and “confirm password” field. When I add “min_length” to my password field and then run the submitted data through my custom clean_confirm_password method, it gives a “Key Error / Password” error.
This occurs when the password field is less than 5 characters, whether the confirm_password field matches or not.
I have tried adding “min_length” to “confirm_password,” but still get the same error.
Everything works fine when I remove “min_length” totally.
Any help is appreciated!
My forms.py file:
class NewUser(forms.Form):
email = forms.EmailField(max_length=75)
first_name = forms.CharField(max_length=45)
last_name = forms.CharField(max_length=45)
password = forms.CharField(min_length=5, max_length=30, widget=forms.PasswordInput(render_value=False))
confirm_password = forms.CharField(max_length=30, widget=forms.PasswordInput(render_value=False))
def clean_confirm_password(self):
confirm_password = self.cleaned_data['confirm_password']
original_password = self.cleaned_data['password']
if original_password != confirm_password:
raise forms.ValidationError("Password doesn't match")
return confirm_password
When you submit a password with fewer than 5 characters, it fails the
min_lengthvalidation sopasswordis not in your form’scleaned_datadictionary. When you try to access the missing key, you get aKeyError.Instead, you should try:
which will return
''if the password is too short.As an aside, a
clean_myfieldnamemethod should only rely on one field. If you want to clean and validate fields that rely on each other, use thecleanmethod for this (see the django docs).