django自定义form验证error
Django:Form中自定义错误提示信息
class LoginForm(forms.Form):
email = forms.EmailField(error_messages={'required':u'邮箱不能为空','invalid':u'请输入正确的邮箱'})
password = forms.CharField(widget=forms.PasswordInput(),error_messages={'required':u'密码不能为空'})
def clean_email(self):
from users.models import User
data=self.cleaned_data['email']
is_exist=User.objects.filter(email=data).exists()
if not is_exist:
raise forms.ValidationError(u"这个邮箱还没有注册哦,请注册后再登录!")
return data
<div><label for="id_email">邮箱</label><span style="margin-left:10px">{{ form.email }}{{form.email.errors}}</span></div>
def clean(self):
from users.models import User
cleaned_data=self.cleaned_data
data_email=cleaned_data.get("email")
data_password=cleaned_data.get("password")
if data_password:
is_exist=User.objects.filter(email=data_email,password=data_password).exists()
if not is_exist:
raise forms.ValidationError(u"密码错误!")
return cleaned_data
class PasswordForm(forms.Form):
uid= forms.CharField(widget=forms.HiddenInput()) #隐藏的类型,用来获取当前用户id
oldpsw = forms.CharField(widget=forms.PasswordInput(),error_messages={'required':u'旧密码不能为空'})
newpsw1 = forms.CharField(widget=forms.PasswordInput(),error_messages={'required':u'新密码不能为空'})
newpsw2 = forms.CharField(widget=forms.PasswordInput(),error_messages={'required':u'密码不能为空'})
def clean(self):
from users.models import User
oldpassword=self.cleaned_data.get('oldpsw')
newpassword1=self.cleaned_data.get('newpsw1')
newpassword2=self.cleaned_data.get('newpsw2')
uid=self.cleaned_data.get('uid')
realpsw=User.objects.get(id=uid).password #通过获取的
if realpsw==oldpassword:
if newpassword1!=newpassword2:
raise forms.ValidationError(u'新密码两次输入不一样,请重新输入')
else:
raise forms.ValidationError(u'旧密码错误,请重新输入')
return self.cleaned_data
<input type="hidden" name="uid" value="{{id}}" /> 这里特别注意name要与PasswordForm定义的名字一致