Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send Custom Error response from serializer in django rest framework?

I want to send a custom response from serializers create view to front-end of my application. I tried rest framework Response tutorials but it does not work. My code is:

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)
like image 495
Salman Ahmed Avatar asked Nov 16 '17 09:11

Salman Ahmed


1 Answers

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)
like image 173
origamic Avatar answered Nov 16 '22 04:11

origamic