django表格的最小密码长度

时间:2016-05-25 21:44:44

标签: python django forms

我正在Django制作一个表单,我正在使用" form.is_valid"得到所有的错误。一切都有效,除了密码的最小值。我的表单代码如下:

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

但是当我输入少于6个字符的密码时,我没有收到验证错误,而是从Django收到错误。该错误是一个关键错误,因为clean_data字典长度超过6个字符时不包含密码。 我也在表单定义中使用了min_length功能,同样的事情发生了

1 个答案:

答案 0 :(得分:3)

如果passwordpassword2无效,则他们不会在cleaned_data。您需要更改clean方法来处理此问题。例如:

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")

您可以在min_length字段中指定password。然后Django将为您验证长度,您可以删除自定义clean方法。

password = forms.CharField(min_length=6, widget=forms.TextInput(attrs={'class' : 'form-control'}))

最后,您的clean_usernameclean_email方法没有做任何事情,因此您可以通过删除它们来简化表单。