Yuri Costa
Yuri Costa

Reputation: 345

Hide a specifc field in update but not in create

I want to show the password field only in create form, but not in the update form. If I remove the password from UserSerializer, it won't appear in both forms.

class UserSerializer(serializers.ModelSerializer):
    subscriptions = SubscriptionSerializer(many=True, read_only=True)
    password = serializers.CharField(
        style={'input_type': 'password'},
        write_only=True
    )

    class Meta:
        model = User
        fields = '__all__'

    def create(self, validated_data):
        user = User.objects.create(**validated_data)
        user.set_password(validated_data["password"])
        user.save()

        return user

Upvotes: 1

Views: 512

Answers (1)

Nafees Anwar
Nafees Anwar

Reputation: 6598

You can remove password field if instance is provided to serializer. That means you are going to update it (instance) or serialize it. In both cases you won't need password field.

class UserSerializer(serializers.ModelSerializer):
    subscriptions = SubscriptionSerializer(many=True, read_only=True)
    password = serializers.CharField(
        style={'input_type': 'password'},
        write_only=True
    )

    class Meta:
        model = User
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.instance:
            self.fields.pop('password')


    def create(self, validated_data):
        user = User.objects.create(**validated_data)
        user.set_password(validated_data["password"])
        user.save()

        return user

Upvotes: 3

Related Questions