Python rest_framework.serializers.ReadOnlyField() Examples

The following are 7 code examples of rest_framework.serializers.ReadOnlyField(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module rest_framework.serializers , or try the search function .
Example #1
Source File: serializers.py    From django-spillway with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_fields(self):
        fields = super(RasterModelSerializer, self).get_fields()
        if not self.Meta.raster_field:
            for name, field in fields.items():
                if isinstance(field, serializers.FileField):
                    self.Meta.raster_field = name
                    break
        fieldname = self.Meta.raster_field
        request = self.context.get('request')
        renderer = getattr(request, 'accepted_renderer', None)
        try:
            obj = self.instance[0]
        except (IndexError, TypeError):
            obj = self.instance
        modelfield = getattr(obj, fieldname, None)
        if (isinstance(renderer, BaseGDALRenderer)
                or not isinstance(modelfield, FieldFile)):
            fields[fieldname] = serializers.ReadOnlyField()
        return fields 
Example #2
Source File: test_basic.py    From django-rest-framework-mongoengine with MIT License 6 votes vote down vote up
def test_method_field(self):
        """
        Properties and methods on the model should be allowed as `Meta.fields`
        values, and should map to `ReadOnlyField`.
        """

        class TestSerializer(DocumentSerializer):
            class Meta:
                model = RegularModel
                fields = ('id', 'method')

        expected = dedent("""
            TestSerializer():
                id = ObjectIdField(read_only=True)
                method = ReadOnlyField()
        """)
        assert repr(TestSerializer()) == expected 
Example #3
Source File: test_basic.py    From django-rest-framework-mongoengine with MIT License 6 votes vote down vote up
def test_missing_field(self):
        """
        Fields that have been declared on the serializer class must be included
        in the `Meta.fields` if it exists.
        """

        class TestSerializer(DocumentSerializer):
            missing = serializers.ReadOnlyField()

            class Meta:
                model = RegularModel
                fields = ('id',)

        with pytest.raises(AssertionError) as exc:
            TestSerializer().fields
        expected = (
            "The field 'missing' was declared on serializer TestSerializer, "
            "but has not been included in the 'fields' option."
        )
        assert expected in str(exc.value) 
Example #4
Source File: test_basic.py    From django-rest-framework-mongoengine with MIT License 6 votes vote down vote up
def test_missing_superclass_field_not_included(self):
        """
        Fields that have been declared on a parent of the serializer class may
        be excluded from the `Meta.fields` option.
        """

        class TestSerializer(DocumentSerializer):
            missing = serializers.ReadOnlyField()

            class Meta:
                model = RegularModel
                fields = '__all__'

        class ChildSerializer(TestSerializer):
            missing = serializers.ReadOnlyField()

            class Meta:
                model = RegularModel
                fields = ('id',)

        ChildSerializer().fields 
Example #5
Source File: test_basic.py    From django-rest-framework-mongoengine with MIT License 6 votes vote down vote up
def test_missing_superclass_field_excluded(self):
        """
        Fields that have been declared on a parent of the serializer class may
        be excluded from the `Meta.fields` option.
        """

        class TestSerializer(DocumentSerializer):
            missing = serializers.ReadOnlyField()

            class Meta:
                model = RegularModel
                fields = '__all__'

        class ChildSerializer(TestSerializer):
            missing = serializers.ReadOnlyField()

            class Meta:
                model = RegularModel
                exclude = ('missing',)

        ChildSerializer().fields 
Example #6
Source File: test_basic.py    From django-rest-framework-mongoengine with MIT License 5 votes vote down vote up
def test_choices_with_nonstandard_args(self):
        class TestSerializer(DocumentSerializer):
            missing = serializers.ReadOnlyField()

            class Meta:
                model = ComplexChoicesModel
                fields = '__all__'

        TestSerializer().fields 
Example #7
Source File: factories.py    From drf-schema-adapter with MIT License 4 votes vote down vote up
def serializer_factory(endpoint=None, fields=None, base_class=None, model=None):

    if model is not None:
        assert endpoint is None, "You cannot specify both a model and an endpoint"
        from .endpoints import Endpoint
        endpoint = Endpoint(model=model)
    else:
        assert endpoint is not None, "You have to specify either a model or an endpoint"

    if base_class is None:
        base_class = endpoint.base_serializer

    meta_attrs = {
        'model': endpoint.model,
        'fields': fields if fields is not None else endpoint.get_fields_for_serializer()
    }
    meta_parents = (object, )
    if hasattr(base_class, 'Meta'):
        meta_parents = (base_class.Meta, ) + meta_parents

    Meta = type('Meta', meta_parents, meta_attrs)

    cls_name = '{}Serializer'.format(endpoint.model.__name__)
    cls_attrs = {
        'Meta': Meta,
    }

    for meta_field in meta_attrs['fields']:
        if meta_field not in base_class._declared_fields:
            try:
                model_field = endpoint.model._meta.get_field(meta_field)
                if isinstance(model_field, OneToOneRel):
                    cls_attrs[meta_field] = serializers.PrimaryKeyRelatedField(read_only=True)
                elif isinstance(model_field, ManyToOneRel):
                    cls_attrs[meta_field] = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
                elif isinstance(model_field, ManyToManyRel):
                    # related ManyToMany should not be required
                    cls_attrs[meta_field] = serializers.PrimaryKeyRelatedField(
                        many=True,
                        required=False,
                        queryset=model_field.related_model.objects.all()
                    )
            except FieldDoesNotExist:
                cls_attrs[meta_field] = serializers.ReadOnlyField()

    try:
        return type(cls_name, (NullToDefaultMixin, base_class, ), cls_attrs)
    except TypeError:
        # MRO issue, let's try the other way around
        return type(cls_name, (base_class, NullToDefaultMixin, ), cls_attrs)