Write only, read only fields in django rest framework

The Django Rest Framework does not have Meta attribute write_only_fields anymore

According to their docs you set write-only fields in extra_kwargs

e.g

class UserSerializer(ModelSerializer):
    """
    ``Serializer`` for ``User`` ..
    """

    class Meta:
        model = User
        fields = ('id', 'email', 'first_name', 'last_name' ,'security_question', 'security_question_answer', 'password', 'is_active', 'is_staff')
        read_only_fields = ('is_active', 'is_staff')
        extra_kwargs = {
            'security_question': {'write_only': True},
            'security_question_answer': {'write_only': True},
            'password': {'write_only': True}
        }

Update

As @AKHIL MATHEW highlighted in his answer below

From DRF v3 onwards, setting a field as read-only or write-only can use serializer field core arguments mentioned as follows.

write_only

Set this to True to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation.

Defaults to False
Eg:

company = serializers.PrimaryKeyRelatedField(write_only=True)

Leave a Comment