首页 > 解决方案 > 自定义字段验证错误不显示字段名称

问题描述

我想实现一个更改密码端点,我有这个视图:

 def update(self, request):
    user_data = {}
    classname = __class__.__name__
    function = 'update'
    try:
        user = request.user
        current = request.data['current']
        password = request.data['password']
        confirm = request.data['confirm']
        serializer = serializers.ChangePasswordSerializer(user, data=request.data)
        if serializer.is_valid():
            serializer.save(updated_by=request.user.username, updated_date=timezone.now())
            logger(request, msg=_("Added Successfully"), level="normal", classname=classname,
                   function=function,
                   user_data=user_data, status=status.HTTP_205_RESET_CONTENT)
            return Response({"message": _("Added Successfully")}, status=status.HTTP_205_RESET_CONTENT)
        logger(request, msg=serializer.errors, level="error", classname=classname, function=function,
               user_data=user_data, status=status.HTTP_422_UNPROCESSABLE_ENTITY)
        return Response({'errors': serializer.errors}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)

    except Exception as ValidationError:
        return Response({"errors": _("Current password is not correct")}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)

    except Exception as e:
        elogger(msg=e.args)
        return Response({"message": _("status500")}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

这是我的序列化程序:

 class ChangePasswordSerializer(DynamicFieldsModelSerializer):
     current = serializers.CharField()
     confirm = serializers.CharField()

    def validate(self, data):
        if data['current'] == data['password']:
            raise serializers.ValidationError("Password and Current password should not be the same")
        if data['confirm'] != data['password']:
            raise serializers.ValidationError("Password and Confirm password did not match")
        return data

    class Meta:
        model = models.User
        fields = ('password', 'current', 'confirm')
        validators = []

    def update(self, instance, validated_data):
        if not instance.check_password(validated_data.get('current')):
            raise serializers.ValidationError("Current password is not correct")
        else:
            instance.set_password(validated_data['password'])
            instance.save()
        return instance

我的第一个问题是我收到此验证错误:

{
   "errors": {
      "non_field_errors": [
         "Password and Current password should not be the same"
      ]
   }
}

我想要我的字段名称而不是“non_field_errors”,我也希望我的检查密码功能在验证功能内,但我不知道如何

标签: pythondjangodjango-rest-framework

解决方案


要获取字段验证错误,您必须从 validate_fieldname 函数中引发错误,ex-validate 确认密码。

class ChangePasswordSerializer(DynamicFieldsModelSerializer):
    current = serializers.CharField()
    confirm = serializers.CharField()

    def validate_current(self, value):
        if value == self.initial_data['password']:
            raise serializers.ValidationError("Password and Current password should not be the same")
        return value

    def validate_confirm(self, value):
        if value != self.initial_data['password']:
            raise serializers.ValidationError("Password and Confirm password did not match")
        return value

    class Meta:
        model = models.User
        fields = ('password', 'current', 'confirm')
        validators = []

    def update(self, instance, validated_data):
        if not instance.check_password(validated_data.get('current')):
            raise serializers.ValidationError("Current password is not correct")
        else:
            instance.set_password(validated_data['password'])
            instance.save()
        return instance

推荐阅读