如何将自定义错误消息附加到Django Rest Framework验证?

时间:2016-07-13 14:38:56

标签: python django django-rest-framework

我有一个简单的视图集,

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    # more properties below.

    def create(self, request, *args, **kwargs):
        serialized_data = UserSerializer(data=request.data)

        if serialized_data.is_valid():
            # method to create a user.
            return Response(status=status.HTTP_201_CREATED)

        else:
            print serialized_data.errors,
            print serialized_data.error_messages

        return Response(status=status.HTTP_404_NOT_FOUND)

使用以下序列化程序

class UserSerializer(serializers.ModelSerializer):
    error_messages = {}

    class Meta:
        model = User
        fields = ("first_name", "email", 'password', "username")
        extra_kwargs = {"password": {"write_only": True}}

    def validate_email(self, value):
        required_value = "" #something that doesn't matter here
        if value is not required_vaue:
            # i want to append the custom error message to the serializer
            error_messages = {"email": {"invalid": "the email is not acceptable!"}} 

        return value

我正在尝试使用自定义validate_email方法将自定义错误消息注入/附加到序列化程序的错误寄存器中,以便我可以将其与serialized_data.error_messages一起使用。

1 个答案:

答案 0 :(得分:1)

您应该提出验证错误:

raise serializers.ValidationError("the email is not acceptable!")

或者尝试编写自定义验证器http://www.django-rest-framework.org/api-guide/validators/#writing-custom-validators

它不在官方文档中,但您可以尝试将错误消息附加到self.errors[field_name]