class TitleValidator(object):
def __init__(self,start):
self.start = start
def __call__(self, value):
if not value.startswith(self.start):
message = '標題必須以 %s 為開頭。' % self.start
raise serializers.ValidationError(message)
def set_context(self, serializer_field):
"""
This hook is called by the serializer instance,
prior to the validation call being made.
"""
# 執行驗證之前呼叫,serializer_fields是當前欄位物件
pass
class UserGroupSerializer(serializers.Serializer):
title = serializers.CharField(error_messages={'required':'組名不能為空'},validators=[TitleValidator('test'),])
class UserGroupView(APIView):
def post(self,request,*args,**kwargs):
ser = UserGroupSerializer(data=request.data)
if ser.is_valid():
print(ser.validated_data['title'])
return HttpResponse("提交成功")
else:
print(ser.errors) # {'title': [ErrorDetail(string='標題必須以 test 為開頭。', code='invalid')]}
return HttpResponse(ser.errors)
class TitleValidator(object):
def __init__(self,start):
self.start = start
def __call__(self, value):
if not value.startswith(self.start):
message = '標題必須以 %s 為開頭。' % self.start
raise serializers.ValidationError(message)
def set_context(self, serializer_field):
"""
This hook is called by the serializer instance,
prior to the validation call being made.
"""
# 執行驗證之前呼叫,serializer_fields是當前欄位物件
pass
class UserGroupSerializer(serializers.ModelSerializer):
class Meta:
model = models.UserGroup
fields = '__all__'
depth = 1
extra_kwargs = {'title': {'validators': [TitleValidator('test'), ]}}
class UserGroupView(APIView):
def post(self,request,*args,**kwargs):
ser = UserGroupSerializer(data=request.data)
if ser.is_valid():
print(ser.validated_data['title'])
return HttpResponse("提交成功")
else:
print(ser.errors) # {'title': [ErrorDetail(string='標題必須以 test 為開頭。', code='invalid')]}
return HttpResponse(ser.errors)
class UserGroupSerializer(serializers.Serializer):
title = serializers.CharField()
# 鉤子函式,validate + “_” + 欄位名稱
def validate_title(self,value):
if not value.startswith("test"):
message = '標題必須以 test 為開頭'
raise serializers.ValidationError(message)
class UserGroupView(APIView):
def post(self,request,*args,**kwargs):
ser = UserGroupSerializer(data=request.data)
if ser.is_valid():
print(ser.validated_data['title'])
return HttpResponse("提交成功")
else:
print(ser.errors) # {'title': [ErrorDetail(string='標題必須以 test 為開頭。', code='invalid')]}
return HttpResponse(ser.errors)