在django rest框架中从序列化器发送自定义错误响应?

时间:2017-11-16 09:17:06

标签: django python-3.x django-models django-rest-framework django-serializer

我想从序列化程序创建一个自定义响应创建视图到我的应用程序的前端。我尝试了休息框架响应教程,但它不起作用。我的代码是:

class UserSerializer(serializers.ModelSerializer):
"""Serializer to serialize user model object"""

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

    def create(self, validated_data):
        """create a new user"""

        firstname = self.initial_data['first_name']
        lastname = self.initial_data['last_name']
        fullname = str(firstname) +" "+ str(lastname)
        email = self.initial_data['username'].lower()

        try:
           customer = User.create(
                name=fullname,
                email=email)

        except Error as e:
            error = {'message': e._message or 'Unknown error'}
            return Response(error,status=status.HTTP_400_BAD_REQUEST)

2 个答案:

答案 0 :(得分:8)

<强> serializers.py

class UserSerializer(serializers.ModelSerializer):
"""Serializer to serialize user model object"""

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

    def create(self, validated_data):
        """create a new user"""

        firstname = validated_data['first_name']
        lastname = validated_data['last_name']
        fullname = str(firstname) +" "+ str(lastname)
        email = validated_data['username'].lower()

        try:
           customer = User.objects.create(
                name=fullname,
                email=email)
           return customer

        except Exception as e:
            error = {'message': ",".join(e.args) if len(e.args) > 0 else 'Unknown Error'}
            raise serializers.ValidationError(error)

答案 1 :(得分:0)

因此,您希望从此视图更改用户的表示形式(JSON响应的形状)。为此,您需要更改序列化程序中的.to_representation(self, obj)方法:

class UserSerializer(serializers.ModelSerializer):
    """Serializer to serialize user model object"""
     class Meta:
        model = User
        fields = ('id', 'username', 'password', 'first_name', 'last_name',)
        write_only_fields = ('id', 'password',)

    def to_representation(self, obj):
        return {
            'firstname': obj.first_name,
            'lastname': obj.last_name,
            'fullname': obj.first_name+' '+obj.last_name,
            'email': obj.username.lower()
        }

这应该意味着每当发出使用此序列化程序的请求时,用户将只能看到JSON中的那4个字段,例如

{
    "firstname":"Salman",
    "lastname": "Ahmed",
    "fullname": "Salman Ahmed",
    "email": "salman_ahmed@email.com"
}

有关此is hidden in their docs here的详细信息。