mirror of
https://github.com/encode/django-rest-framework.git
synced 2024-11-10 19:56:59 +03:00
Absolute URLs for file fields
This commit is contained in:
parent
657d1de032
commit
d1b2c8ac7f
|
@ -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
|
||||
|
||||
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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.
|
||||
# --------------------------------
|
||||
|
||||
|
|
Loading…
Reference in New Issue
Block a user