Discussion:
Specifying required=False on a custom field
Richard Hughes
2018-06-21 18:39:24 UTC
Permalink
A String List Field declared outside of the Serializer Class with
required=False does not honor the required=False property when instantiated
in the Serializer Class. The 'field is required' error is returned.

The required=False has to be declared when the Field is being
instantiated. Is this a bug or expected behavior?

class StringListField(serializers.ListField):
child = serializers.CharField()


def to_representation(self, data):
return [x.name for x in data.all()]

class EngSerializer(serializers.ModelSerializer):


class Meta:
model = EngineeringFileModel
fields = '__all__'
depth = 2
read_only_fields = ('last_edited_date', 'base_name', 'file_type',
'size', 'date_added', 'mime')


grid_cells = StringListField(required=False)
--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-framework+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Jason
2018-06-21 23:44:40 UTC
Permalink
If you look at the implementation for Field,
https://github.com/encode/django-rest-framework/blob/master/rest_framework/fields.py#L307-L316

you can see it is initialized with required = None, but its included as a
kwarg for overriding. Since required is not an instance or class
attribute, if you override it in a re-implementation, it won't have any
effect
--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-framework+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Loading...