Reputation: 77
I am making a form in Django and I am using the "form.is_valid" to get all the error. Everything works except the minimum value for the password. I have following code for my form:
class RegisterationForm (forms.Form):
first_name = forms.CharField(initial ='' ,widget=forms.TextInput(attrs={'class' : 'form-control'}),max_length = 20)
last_name = forms.CharField(initial ='' ,widget=forms.TextInput(attrs={'class' : 'form-control'}),max_length = 20)
username = forms.CharField(initial ='' ,widget=forms.TextInput(attrs={'class' : 'form-control'}),min_length = 5,max_length = 20)
email = forms.EmailField(initial ='' ,widget=forms.TextInput(attrs={'class' : 'form-control'}))
password = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control'}))
password2 = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control'}))
def clean(self):
cleaned_data = super(RegisterationForm, self).clean()
password = self.cleaned_data['password']
password2 = self.cleaned_data['password2']
if password and password != password2:
raise forms.ValidationError("passwords do not match")
return self.cleaned_data
def clean_username(self):
username = self.cleaned_data['username']
return username
def clean_email(self):
email = self.cleaned_data['email']
return email
def clean_password(self):
password= self.cleaned_data['password']
if len(password) < 6:
raise forms.ValidationError("Your password should be at least 6 Characters")
return password
but here when I enter a password less than 6 characters, instead of getting a validation error I get an error from Django. The error is a key error which is caused because the cleaned_data dictionary does not contain the password when it's longer than 6 chars. I also used the min_length feature in form definition as well and the same thing happened.
Upvotes: 0
Views: 5278
Reputation: 309049
If password
or password2
is not valid, then they will not be in cleaned_data
. You need to change your clean
method to handle this. For example:
def clean(self):
cleaned_data = super(RegisterationForm, self).clean()
password = self.cleaned_data.get('password')
password2 = self.cleaned_data.get('password2')
if password and password2 and password != password2:
raise forms.ValidationError("passwords do not match")
You could specify min_length
in your password
field. Then Django will validate the length for you, and you can remove your custom clean
method.
password = forms.CharField(min_length=6, widget=forms.TextInput(attrs={'class' : 'form-control'}))
Finally, your clean_username
and clean_email
methods are not doing anything so you can simplify your form by removing them.
Upvotes: 6