diff --git a/rest_framework/fields.py b/rest_framework/fields.py index fee6080aa..f7ea3b0c2 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -150,10 +150,6 @@ class Field(object): messages.update(error_messages or {}) self.error_messages = messages - for validator in validators: - if getattr(validator, 'requires_context', False): - validator.serializer_field = self - def bind(self, field_name, parent): """ Initializes the field name and parent for the field instance. @@ -264,6 +260,8 @@ class Field(object): """ errors = [] for validator in self.validators: + if getattr(validator, 'requires_context', False): + validator.serializer_field = self try: validator(value) except ValidationError as exc: @@ -907,7 +905,11 @@ class FileField(Field): def to_representation(self, value): if self.use_url: - return settings.MEDIA_URL + value.url + url = settings.MEDIA_URL + value.url + request = self.context.get('request', None) + if request is not None: + return request.build_absolute_uri(url) + return url return value.name diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 09ad376a2..0faa56718 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -428,7 +428,6 @@ class ModelSerializer(Serializer): queryset=model_class._default_manager, fields=unique_together ) - validator.serializer_field = self validators.append(validator) for parent_class in model_class._meta.parents.keys(): @@ -438,7 +437,6 @@ class ModelSerializer(Serializer): queryset=parent_class._default_manager, fields=unique_together ) - validator.serializer_field = self validators.append(validator) return validators diff --git a/tests/test_fields.py b/tests/test_fields.py index aa8c3a68c..bbd9f93d8 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -953,6 +953,23 @@ class TestListField(FieldValues): field = fields.ListField(child=fields.IntegerField()) +# Tests for FieldField. +# --------------------- + +class MockRequest: + def build_absolute_uri(self, value): + return 'http://example.com' + value + + +class TestFileFieldContext: + def test_fully_qualified_when_request_in_context(self): + field = fields.FileField(max_length=10) + field._context = {'request': MockRequest()} + obj = MockFile(name='example.txt', url='/example.txt') + value = field.to_representation(obj) + assert value == 'http://example.com/example.txt' + + # Tests for SerializerMethodField. # --------------------------------