Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions rest_framework/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -1540,8 +1540,7 @@ def to_internal_value(self, data):
file_object = super(ImageField, self).to_internal_value(data)
django_field = self._DjangoImageField()
django_field.error_messages = self.error_messages
django_field.to_python(file_object)
return file_object
return django_field.clean(file_object)


# Composite field types...
Expand Down
22 changes: 16 additions & 6 deletions tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

import rest_framework
from rest_framework import compat, serializers
from rest_framework.fields import is_simple_callable
from rest_framework.fields import DjangoImageField, is_simple_callable

try:
import pytz
Expand Down Expand Up @@ -1700,15 +1700,24 @@ class TestFieldFieldWithName(FieldValues):
field = serializers.FileField(use_url=False)


def ext_validator(value):
if not value.name.endswith('.png'):
raise serializers.ValidationError('File extension is not allowed. Allowed extensions is png.')


# Stub out mock Django `forms.ImageField` class so we don't *actually*
# call into it's regular validation, or require PIL for testing.
class FailImageValidation(object):
class PassImageValidation(DjangoImageField):
default_validators = [ext_validator]

def to_python(self, value):
raise serializers.ValidationError(self.error_messages['invalid_image'])
return value


class PassImageValidation(object):
class FailImageValidation(PassImageValidation):
def to_python(self, value):
if value.name == 'badimage.png':
raise serializers.ValidationError(self.error_messages['invalid_image'])
return value


Expand All @@ -1718,7 +1727,8 @@ class TestInvalidImageField(FieldValues):
"""
valid_inputs = {}
invalid_inputs = [
(MockFile(name='example.txt', size=10), ['Upload a valid image. The file you uploaded was either not an image or a corrupted image.'])
(MockFile(name='badimage.png', size=10), ['Upload a valid image. The file you uploaded was either not an image or a corrupted image.']),
(MockFile(name='goodimage.html', size=10), ['File extension is not allowed. Allowed extensions is png.'])
]
outputs = {}
field = serializers.ImageField(_DjangoImageField=FailImageValidation)
Expand All @@ -1729,7 +1739,7 @@ class TestValidImageField(FieldValues):
Values for an valid `ImageField`.
"""
valid_inputs = [
(MockFile(name='example.txt', size=10), MockFile(name='example.txt', size=10))
(MockFile(name='example.png', size=10), MockFile(name='example.png', size=10))
]
invalid_inputs = {}
outputs = {}
Expand Down