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