博客五部曲之三 - 博客RESTful
1515 浏览 5 years, 9 months
27 Serializer Validation
版权声明: 转载请注明出处 http://www.codingsoho.com/Serializer Validation
我们需要两次输入email来验证。
添加EmailField,实例为email和email2,并添加validation函数
默认的email field是可以非空的,我们希望它和confirm email一样必填,所以覆盖email定义
src/accounts/api/serializers.py
from rest_framework.serializers import (
EmailField,
class UserCreateSerializer(ModelSerializer):
email = EmailField(label='Email Address')
email2 = EmailField(label='Confirm Email')
def validate(self, data):
# email = data['email']
# user_qs = User.objects.filter(email=email)
# if user_qs.exists():
# raise ValidationError("This user has already registered.")
return data
def validate_email(self, value):
data = self.get_initial()
email1 = data.get("email2")
email2 = value
if email1 != email2:
raise ValidationError("Emails must match.")
user_qs = User.objects.filter(email=email2)
if user_qs.exists():
raise ValidationError("This user has already registered.")
return value
def validate_email2(self, value):
data = self.get_initial()
email1 = data.get("email")
email2 = value
if email1 != email2:
raise ValidationError("Emails must match.")
return value
如果用户已存在,那么同样不能保存,这个验证可以放在validate函数里实现,或者如上面那样,放在validate_email函数里。
再回头看forms里的处理,基本是一样的
class UserRegisterForm(forms.ModelForm):
email = forms.EmailField(label="Email")
email2 = forms.EmailField(label="Confirm Email")
password = forms.CharField(widget=forms.PasswordInput) # change widget
class Meta:
model = User
fields = [
"username",
"email",
"email2",
"password",
]
def clean_email2(self):
email = self.cleaned_data.get('email')
email2 = self.cleaned_data.get('email2')
if email != email2:
raise forms.ValidationError("Emails must match")
email_qs = User.objects.filter(email=email)
if email_qs.exists():
raise forms.ValidationError("This email has been already registered")
return email