[英]Testing an ImageField in DRF
I am using Django Imagekit in models.py: 我在models.py中使用Django Imagekit:
from imagekit.models import ProcessedImageField
class AltroUser(models.Model):
first_name = models.CharField(_('first name'), max_length=30)
image = ProcessedImageField(upload_to='media/path',
default='user_default.jpg',
processors=[ResizeToFill(640, 640)],
format='JPEG',
options={'quality': 60})
serializers.py: serializers.py:
class UserRegistrationSerializer(Serializer):
first_name = serializers.CharField()
image = serializers.ImageField()
I am trying to test the image field. 我正在尝试测试图像字段。 I have tried following methods:
我尝试了以下方法:
def get_test_image():
try:
image = DjangoFile(open(os.path.join(django_settings.MEDIA_ROOT, 'user_default.jpg'),
mode='rb'))
return image
except (OSError, IOError) as e:
return None
def get_test_image1():
file = io.BytesIO()
image = Image.new('RGBA', size=(100, 100), color=(155, 0, 0))
image.save(file, 'png')
file.name = 'test.png'
file.seek(0)
return SimpleUploadedFile('abc.jpg', file.read())
def get_test_image2():
path = os.path.join(django_settings.MEDIA_ROOT, 'user_default.jpg')
file = File(open(path, 'r+b'))
return SimpleUploadedFile('abc.jpg', file.read())
I have tried calling the above three methods to set the value of the image key but none of them worked. 我尝试调用上述三种方法来设置图像键的值,但是它们都不起作用。 For
get_test_image()
, I get a response "The submitted file is empty." 对于
get_test_image()
,我得到一个响应“提交的文件为空。”
For get_test_image1()
and get_test_image2()
, I get a response "The submitted file is empty."
对于
get_test_image1()
和get_test_image2()
,我得到一个响应"The submitted file is empty."
with an exception before in the data image field '_io.BytesIO' object has no attribute 'encoding'
. 但之前在数据映像字段
'_io.BytesIO' object has no attribute 'encoding'
。
I don't understand what am I missing. 我不明白我在想什么。 Please help.
请帮忙。
Here's an example of what I'm using to generate test image: 这是我用来生成测试图像的示例:
from StringIO import StringIO
from PIL import Image
from django.core.files import File
def get_image_file(name='test.png', ext='png', size=(50, 50), color=(256, 0, 0)):
file_obj = StringIO()
image = Image.new("RGBA", size=size, color=color)
image.save(file_obj, ext)
file_obj.seek(0)
return File(file_obj, name=name)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.