1

I have a simple viewset,

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)

which uses the following serializer,

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

I'm trying to inject/append the custom error message to the error register of the serializer with the custom validate_email method, so that I can use it with serialized_data.error_messages.

1 Answer 1

1

You should raise validation error:

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

Or try writing custom validators http://www.django-rest-framework.org/api-guide/validators/#writing-custom-validators

It is not in the official documentation, but you can try appending error message to self.errors[field_name]

Sign up to request clarification or add additional context in comments.

1 Comment

can I append the errors to serialized_data.error_messages??

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.