ImageField and API Test Case

219 views
Skip to first unread message

they.said.thi...@gmail.com

unread,
Mar 27, 2017, 11:08:31 AM3/27/17
to Django REST framework
Hello, suppose I have the following code:

class BizProfile(models.Model):
    title = models.CharField(max_length=100)
    description = models.CharField(max_length=500, default="", blank=True)
    profile_image = models.ImageField(max_length=200, blank=True, null=True)
    banner_image = models.ImageField(max_length=200, blank=True, null=True)

class BizHasPhoto(models.Model):
    biz_profile = models.ForeignKey(BizProfile)
    photo = models.ImageField(max_length=200)
    description = models.CharField(max_length=300, default="", blank=True)

serializers and views are default.

I get HTTP 200 when running the following test:

profile_image = open('valid_profile_image.jpg', 'rb')
banner_image = open('valid_banner_image.jpg', 'rb')
data = {
    'profile_image': profile_image,
    'banner_image': banner_image
}
response = self.client.patch(url, data, format='multipart')

Later on when doing a GET to the biz_profile, I verify that response.data['profile_image'] is 
'http://testserver/media/valid_profile_image.jpg' and response.data['banner_image'] is
'http://testserver/media/valid_banner_image.jpg', so I guess my views, urls and parsers are alright.

But at the same time I get HTTP 400 with "the submitted file is empty" when running the following test:

biz_profile_url = reverse('url_to_reverse_here', args=[biz_profile.pk])
photo = open('valid_photo.jpg', 'rb')
data = {
    'biz_profile': biz_profile_url,
    'description': 'a description goes here',
    'photo': banner_image
}
response = self.client.post(url, data, format='multipart')

Am I doing something wrong? Thanks in advance.

they.said.thi...@gmail.com

unread,
Mar 27, 2017, 4:26:07 PM3/27/17
to Django REST framework
If anyone arrives here, I fixed this by marking setting the 'photo' serializer field as 'required': False and 'allow_null': True, plus adding:

def perform_create(self, serializer):
    return serializer.save(photo=self.request.data('upload_image'))

I have no idea why, but it's important to leave 'photo' data field as blank, and upload the image using another field, in this example: 'upload_image'.

Hope it helps some space cowboy.
Reply all
Reply to author
Forward
0 new messages