forms.py
class RegisterForm(forms.Form):
username = forms.CharField(min_length=4, max_length=16,
error_messages={'required': u'please input username', 'min_length': 'username is too short',
'max_length': 'username is too long'})
password = forms.CharField(min_length=6, max_length=16,
error_messages={'required': u'please input password', 'min_length': 'password is too short',
'max_length': 'password is too long'})
views.py
def register(request):
if request.method == "POST":
form = RegisterForm(request.POST)
if form.is_valid():
print form
return HttpResponse("success")
else:
print form.errors
return HttpResponse("error")
else:
return render(request, "register.html")
在views.py中,我需要获取错误内容,例如“请输入用户名”,“密码太短”, 但是,form.erros是html部分,你可以参考图片。
答案 0 :(得分:0)
你可以这样做:
def clean_username(self):
if len(username)<1:
msg = u"Please enter username."
self._errors["username"] = self.error_class([msg])
return False
return self.cleaned_data["username"]
def clean_password(self):
if len(password)<6:
msg = u"Password is too short."
self._errors["password"] = self.error_class([msg])
return False
return self.cleaned_data["password"]