Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have 2 models : User & UserSummary. UserSummary has a foreign key to User. I just noticed that if I set depth= 1 within UserSummarySerializer, the password field is included in the output. It's hashed, but it would still be best to exclude this field.

To hide the password field, I've just set the user field explicitly in the serializer, just like this :

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

    class Meta:
        model = models.User
       extra_kwargs = {'password': {'write_only': True}}
        exclude = ('groups', 'last_login', 'is_superuser', 'user_permissions', 'created_at')

    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


class UserSummarySerializer(serializers.ModelSerializer):
    user = UserSerializer()

    class Meta:
        model = models.UserSummary
        fields = '__all__'
        depth = 1

The downside of this way of doing is that, the field password is not available anymore on the POST request when creating a new user.

How could I hide the password field on the GET request of UserSummary but display it in the POST request of User ?

like image 807
kabrice Avatar asked Jan 27 '18 21:01

kabrice


People also ask

What is the difference between ModelSerializer and HyperlinkedModelSerializer?

The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.

What is Restapi in Django?

REST APIs are an industry-standard way for web services to send and receive data. They use HTTP request methods to facilitate the request-response cycle and typically transfer data using JSON, and more rarely - HTML, XML and other formats.

Is there any password field in Django?

The Django's Forms The above form has two inputs - a text field named username (the name attribute in the html input field is what determines the name of input field) and a password field named password - and a submit button. The form uses POST method to submit form data to server.

What is Django REST Framework What are key features of it?

Django REST framework is an open source, flexible and fully-featured library with modular and customizable architecture that aims at building sophisticated web APIs and uses Python and Django.


1 Answers

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}}
like image 95
Aniket A. Aryamane Avatar answered Nov 06 '22 21:11

Aniket A. Aryamane