[Solved]-Hide password field in GET but not POST in Django REST Framework where depth=1 in serializer

7👍

This is complicated when you put all the function serializer to one, I would create a UserCreateSerializer in this scenario:

class UserCreateSerializer(serializers.ModelSerializer):
    """A serializer for our user profile objects."""

    class Meta:
        model = models.User
        extra_kwargs = {'password': {'write_only': True}}
        fields = ['username', 'password', 'email', 'firstname', 'lastname', 'mobile'] # there what you want to initial.

    def create(self, validated_data):
        """Create and return a new user."""

        user = models.User(
            email = validated_data['email'],
            firstname = validated_data['firstname'],
            lastname = validated_data['lastname'],
            mobile = validated_data['mobile']
        )

        user.set_password(validated_data['password'])
        user.save()

        return user

Then you can use the UserCreateSerializer in your UserCreateAPIView.

18👍

The trick here is to include the ‘password’ field in the “fields” tuple so that password shows in BOTH ‘GET’ and ‘POST’, and then add ‘extra_kwargs’ to force ‘password’ field ONLY to appear in ‘POST’ form. Code as below:

class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('url', 'username', 'email',
              'is_active', 'is_staff', 'is_superuser', 'password',)

        # These fields are displayed but not editable and have to be a part of 'fields' tuple
        read_only_fields = ('is_active', 'is_staff', 'is_superuser',)

        # These fields are only editable (not displayed) and have to be a part of 'fields' tuple
        extra_kwargs = {'password': {'write_only': True, 'min_length': 4}}

5👍

class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User

    def to_representation(self, obj):
        rep = super(UserSerializer, self).to_representation(obj)
        rep.pop('password', None)
        return rep

1👍

To Make your password to not show password, you need to change style like following-

password = serializers.CharField(
    style={'input_type': 'password'}
    )

That’s it. I hope it helps.

👤Yash

1👍

Make Changes in Serializers.py file

password = serializers.CharField( 
           style={'input_type': 'password'},
           min_length=6, 
           max_length=68, 
           write_only=True)

Leave a comment