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


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']


        return user

Then you can use the UserCreateSerializer in your UserCreateAPIView.


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}}


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


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.



Make Changes in Serializers.py file

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

Leave a comment