如何在Django Rest框架中将错误响应发送回客户端?

时间:2019-07-08 11:15:57

标签: javascript django vue.js django-rest-framework

我是Django rest框架的新手,并尝试将自定义错误消息发送回使用VueJS的客户端。

我按照here给出的答案进行操作,但是我无法在客户端收到错误消息。

客户端

auth.phoneVerification(this.fullName, this.mobileNo, this.email)
                .then((response)=>{
                  console.log(response.data)
                })
                .catch((error)=>{
                  console.log("Error is ", error)
                })

服务器端

serializers.py

class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = InterestedUser
        fields = ('full_name', 'phone_no', 'email')

    def __init__(self, *args, **kwargs):
        super(UserSerializer, self).__init__(*args, **kwargs)
        self.fields['full_name'].error_messages['required'] = 'Please provide your full name.'
        self.fields['phone_no'].error_messages['required'] = 'Please provide your mobile number.'
        self.fields['email'].error_messages['required'] = 'Please provide your email id.'

views.py

class UserView(GenericAPIView):
    serializer_class = UserSerializer

    def post(self, request):
        serializer = self.get_serializer(data=request.data)
        print("requested data is ", request.data)

        if not serializer.is_valid():
            raise serializers.ValidationError(serializer.errors)

        print("serialiser errors are ",serializer.errors)

在控制台中,我无法收到serializer.errors提供的消息

1 个答案:

答案 0 :(得分:0)

您可以返回带有适当数据的任何Django响应,例如:

let y = 3;
const square = x => (const y = x ** 2, y);
console.log(square(2), y);