2
votes

I'm try to test my model with ImageField, for this purpose i'm reading .jpg file in binary mode and save in the model. I find a lot of question in StackOverflow, but nothing seems to work for me.

testImagePath = os.path.join(settings.BASE_DIR, 'test_image_folder/test_image.jpg')

"image" : SimpleUploadedFile(name='test_image.jpg', content=open(testImagePath, 'rb').read(), content_type='image/jpeg')

error:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

test.py

class Test(TestCase):

    testUser = {
           "username": "TestUser",
           "email": "[email protected]",
           "password": "TestUserPassword",
           "confirm_password": "TestUserPassword"
        }
    testAlbum = {
            "owner" : testUser['username'],
            "name" : "Test Album"
        }
    testImagePath = os.path.join(settings.BASE_DIR, 'test_image_folder/test_image.jpg')
    testPhoto = {
            "owner" : testUser['username'],
            "album" : testAlbum['name'],
            "name" : "Test Photo",
            "image" : SimpleUploadedFile(name='test_image.jpg', content=open(testImagePath, 'rb').read(), content_type='image/jpeg')
        }
    def setUp(self):
        self.client = APIClient()
        self.registerTestUser()
...

    def test_photos_urls(self):
        response = self.client.post('/api/photos/', self.testPhoto, format="json")
        self.assertEqual(response.status_code, status.HTTP_201_CREATED, msg=response.content)

serializer:

class PhotoSerializer(serializers.HyperlinkedModelSerializer):
    album = serializers.HyperlinkedRelatedField(view_name='album-detail', queryset=Album.objects)
    owner = serializers.ReadOnlyField(source='owner.username')

    class Meta:
        model = Photo
        fields = ('pk', 'name', 'image', 'creation_date', 'owner', 'album',)
        read_only_fields=('creation_date',)

view:

class PhotoViewSet(viewsets.ModelViewSet):
    queryset = Photo.objects.all()
    serializer_class = PhotoSerializer 
    permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,)

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)

model:

class Photo(models.Model):
    album = models.ForeignKey(Album, related_name='photos', on_delete=models.CASCADE)
    owner = models.ForeignKey(User,  related_name='user_photos', on_delete=models.CASCADE)
    name = models.CharField(max_length=80, default='New photo')
    image = models.ImageField(name, upload_to=get_image_path)
    creation_date = models.DateField(auto_now_add=True)

    def __str__(self):
        return self.name

    class Meta:
        ordering = ['creation_date', ]

Full traceback of error:

Traceback (most recent call last): File "D:\code\active\Python\Django\photo-hub\photo-hub\api\tests.py", line 66, in test_photos_urls response = self.client.post('/api/photos/', self.testPhoto, format="json") File "C:\Users\User\AppData\Local\Programs\Python\Python35-32\lib\site-packages\rest_framework\test.py", line 172, in post path, data=data, format=format, content_type=content_type, **extra) File "C:\Users\User\AppData\Local\Programs\Python\Python35-32\lib\site-packages\rest_framework\test.py", line 93, in post data, content_type = self._encode_data(data, format, content_type) File "C:\Users\User\AppData\Local\Programs\Python\Python35-32\lib\site-packages\rest_framework\test.py", line 65, in _encode_data ret = renderer.render(data) File "C:\Users\User\AppData\Local\Programs\Python\Python35-32\lib\site-packages\rest_framework\renderers.py", line 103, in render separators=separators File "C:\Users\User\AppData\Local\Programs\Python\Python35-32\lib\json__init__.py", line 237, in dumps **kw).encode(obj) File "C:\Users\User\AppData\Local\Programs\Python\Python35-32\lib\json\encoder.py", line 198, in encode chunks = self.iterencode(o, _one_shot=True) File "C:\Users\User\AppData\Local\Programs\Python\Python35-32\lib\json\encoder.py", line 256, in iterencode return _iterencode(o, 0) File "C:\Users\User\AppData\Local\Programs\Python\Python35-32\lib\site-packages\rest_framework\utils\encoders.py", line 54, in default return obj.decode('utf-8') UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

1
Try this as: testImagePath = os.path.join(settings.BASE_DIR, 'test_image_folder') - Amandeep Dhiman
And after that read folder instead of file? - Rodion
Please mention a bit more details of your problem. please show your code(views.py, models.py,template etc) for more details. - Amandeep Dhiman

1 Answers

0
votes

ImageField need to obtain file, not data. This solve the problem:

"image" : open(os.path.join(settings.BASE_DIR, 'test_image_folder/test_image.jpg'), 'rb')