0

我有一个允许用户创建用户帐户的表单。我还强制规定最小密码长度为 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},)

我的表格.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>
4

2 回答 2

3

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

于 2013-05-20T10:48:07.933 回答
1

你的if情况不正确:

代替

if len(password) > self.MIN_LENGTH:

利用

if len(password) <= self.MIN_LENGTH:
                #<---- changed condition
于 2013-05-20T10:50:33.060 回答