andilabs
andilabs

Reputation: 23361

django rest framework combination of write_only=True and required=False not working

In my serializer based on Django Rest Framework serializers.ModelSerializer I am declaring field, which will be only considered during importing some data (deserialization) and which is not reflecting any model field.

new_number = serializers.CharField(
    write_only=True, required=False,
    allow_null=True, default=''
)

From Django Rest Framework documentation:

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

required

Normally an error will be raised if a field is not supplied during deserialization. Set to false if this field is not required to be present during deserialization.

Setting this to False also allows the object attribute or dictionary key to be omitted from output when serializing the instance. If the key is not present it will simply not be included in the output representation.

Defaults to True.

The problem I ancounter is that when this field is empty, I get error: {'new_number': ['This field can not be blank']}

I am running:

djangorestframework==3.2.3
Django==1.8.4

Upvotes: 2

Views: 2270

Answers (1)

Rahul Gupta
Rahul Gupta

Reputation: 47906

You need to pass allow_blank=True argument in the new_number serializer field. Its default value is False.

new_number = serializers.CharField(
    write_only=True, required=False, allow_blank=True, # allow empty string as a valid value
    default=''
)

From the allow_blank argument documentation:

allow_blank - If set to True then the empty string should be considered a valid value. If set to False then the empty string is considered invalid and will raise a validation error. Defaults to False.

Also, you should use allow_blank instead of allow_null here and not both because as this will mean there will be 2 types of empty value possible.

The allow_null option is also available for string fields, although its usage is discouraged in favor of allow_blank. It is valid to set both allow_blank=True and allow_null=True, but doing so means that there will be two differing types of empty value permissible for string representations, which can lead to data inconsistencies and subtle application bugs.

Upvotes: 1

Related Questions