文章目录
错误复现
serializers.py
bash
class LoginSerializer(serializers.Serializer):
username = serializers.CharField(min_length=5, max_length=10, help_text="账号")
password = serializers.CharField(min_length=5, max_length=10, help_text="密码")
# 校验用户名
def validate_username(self, value):
if not re.match(r'^[a-zA-Z0-9_-]{5,10}$', value):
raise serializers.ValidationError("请输入5-20的用户名!")
# 校验密码
def validate_password(self, value):
if not re.match(r'^[a-zA-Z0-9_-]{6,10}$', value):
raise serializers.ValidationError("请输入6-20的密码!")
view.py
bash
class LoginGenericAPIView(GenericAPIView):
queryset = User.objects.all()
serializer_class = LoginSerializer
permission_classes = [AllowAny]
def post(self, request):
# 获取序列化器
serializer = self.get_serializer(data=request.data)
print(request.data)
# 验证数据
if not serializer.is_valid():
return Response(serializer.errors)
print(serializer)
print(serializer.data)
return Response(serializer.data)
错误
请求可以获取到value但是验证完毕数据一直为None
解决方案
一定不要像我一样粗心
bash
validate_<field_name>验证完毕没有返回Value
正确的代码
bash
class LoginSerializer(serializers.Serializer):
username = serializers.CharField(min_length=5, max_length=10, help_text="账号")
password = serializers.CharField(min_length=5, max_length=10, help_text="密码")
# 校验用户名
def validate_username(self, value):
if not re.match(r'^[a-zA-Z0-9_-]{5,10}$', value):
raise serializers.ValidationError("请输入5-20的用户名!")
return value
# 校验密码
def validate_password(self, value):
if not re.match(r'^[a-zA-Z0-9_-]{6,10}$', value):
raise serializers.ValidationError("请输入6-20的密码!")
return value