当需要最小长度密码时,Django无法引发错误

时间:2013-05-20 10:44:41

标签: django django-forms

我有一个允许用户创建用户帐户的表单。我还强制执行最小密码长度为8,当违反该密码时,将引发错误。问题是,每当违反最小密码长度8时,它不会引发错误。

有人可以帮助我。

def Registration(request):  
    form = UserRegistration()
    if request.method =='POST':
        form = UserRegistration(request.POST)
        if form.is_valid():
            user = User.objects.create_user(
                username=form.cleaned_data['username'], 
                email=form.cleaned_data['email'], 
                password=form.cleaned_data['password']
                )
            user.is_active = True
            user.save()
             return render(request,'choose.html',{'form':form})

    return render(request, 'register.html', {'form': form},)

my forms.py

 class UserRegistration(forms.Form):
    username = forms.CharField()
    email = forms.EmailField(error_messages={'required':'Error Missing Field , Please Fill this Field'})

    password = forms.CharField(
    widget=forms.PasswordInput(render_value=False)
    )

    MIN_LENGTH = 8

    def clean_password(self):
            password = self.cleaned_data['password']

            if len(password) > self.MIN_LENGTH:
                    raise forms.ValidationError("The new password must be at least %d characters long." % self.MIN_LENGTH)

            return password

我的模板

<form method ="POST">
    {% csrf_token %}


<span id="error">{{form.username.errors}}</span>
<span id="error2">{{form.email.errors}}</span>
<span id="error3">{{form.password.errors}}</span>

{{form.username}}
{{form.email}}
{{form.password}}
    <input type = "submit" value= "save" id="box2"/>
</form>

2 个答案:

答案 0 :(得分:3)

clean_new_password1永远不会被调用,因为new_password1不是模型字段,将其更改为clean_password,或调用super来覆盖任何默认检查

答案 1 :(得分:1)

您的if条件不正确:

而不是

if len(password) > self.MIN_LENGTH:

使用

if len(password) <= self.MIN_LENGTH:
                #<---- changed condition