2016-05-25 28 views
0

我正在Django中创建一个表单,并使用“form.is_valid”来获取所有错误。除了密码的最小值以外,一切都正常。我有以下代码为我的形式:django表单的密码的最小长度

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中得到一个错误。该错误是一个重要的错误,这是由于在长度超过6个字符时,cleared_data字典不包含密码而导致的。 我也在表单定义中使用了min_length特性,同样的事情发生在

回答

2

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

你可以指定你的passwordmin_length。然后Django会验证您的长度,并且您可以删除自定义的clean方法。

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

最后,您clean_usernameclean_email方法没有做任何事情,所以你可以删除它们简化形式。

+0

是的它是有道理的 –