Karesh A
Karesh A

Reputation: 1751

Django rest remove password after creation

I have user create serializer but still it is returning the password and c_password fields. How can I remove that to response.

class UserCreateSerializer(ModelSerializer):
    phone = CharField(label='Phone number')
    password = CharField(label='password')
    c_password = CharField(label='confirm passowrd')

    class Meta:
        model = User
        fields = [
            'phone',
            'username',
            'password',
            'c_password'
        ]

        extra_kwargs = {"password": {"write_only": True},
                        "c_password": {"write_only": True}}

    def create(self, validated_data):
        phone = validated_data['phone']
        username = validated_data['username']
        password = validated_data['c_password']

        user_obj = User(phone=phone, username=username)
        user_obj.set_password(password)
        user_obj.save()

        return validated_data

class UserCreateAPIView(CreateAPIView):
    permission_classes = [AllowAny]
    serializer_class = UserCreateSerializer
    queryset = User.objects.all()

And I also tried to add the perform_create method and returned the custom Response object. but it is returning the serializer object with passwords.

Upvotes: 2

Views: 741

Answers (1)

jape
jape

Reputation: 2901

You're returning the validated data in your create method. If you only want the user object, simply return that. For example:

class UserCreateSerializer(ModelSerializer):
    phone = CharField(label='Phone number')
    password = CharField(label='password')
    c_password = CharField(label='confirm passowrd')

    class Meta:
        model = User
        fields = [
            'phone',
            'username',
            'password',
            'c_password'
        ]

        extra_kwargs = {"password": {"write_only": True},
                        "c_password": {"write_only": True}}

    def create(self, validated_data):
        phone = validated_data['phone']
        username = validated_data['username']
        password = validated_data['c_password']

        user_obj = User(phone=phone, username=username)
        user_obj.set_password(password)
        user_obj.save()

        return user_obj

Upvotes: 3

Related Questions