class LoginForm(forms.Form):
user = fields.CharField()
pwd = fields.CharField(validators=[])
def clean_user(self):
c = models.UserInfo.objects.filter(name=self.cleand_data['user']).count()
if not c:
return self.cleand_data['user']
else:
raise ValidationError('用户名已经存在',code='xxx')
def clean_pwd(self):
return self.cleand_data['email']
def clean(self):
c = models.UserInfo.objects.filter(name= self.cleand_data['user'],pwd=self.cleand_data['pwd']).count()
if c:
return self.cleand_data
else:
raise ValidationError('用户名或密码错误')
def _post_clean(self):
pass
如果单独验证每个字段是否有错误,需要自定义钩子
clean_字段名称
如果做整体的验证需要clean
钩子__post_clean
clean验证完之后
from django.core.exceptions import NON_FIELD_ERRORS
obj = RegisterForm(request.POST)
if obj.is_valid():
obj.cleand_data
else:
obj.errors
{
'user':[{'code':'required','message':'xxxx'}],
'pwd':[{'code':'required','message':'xxxx'}],
# 上面每个字段的错误信息放在里面,那clean总的错误信息放在哪里?
'__all__':[], # 特殊的整体错误信息,放在这里
# NON_FIELD_ERRORS:[], 和 __all__ 一个意思。
}