Upload Image in Django ImageField
<p>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.</p>

<pre><code>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')
</code></pre>

<p>error:</p>

<blockquote>
  <p>UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position
  0: invalid start byte</p>
</blockquote>

<p>test.py</p>

<pre><code>class Test(TestCase):

    testUser = {
           "username": "TestUser",
           "email": "TestUser@mail.com",
           "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)
</code></pre>

<p>serializer:</p>

<pre><code>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',)
</code></pre>

<p>view:</p>

<pre><code>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)
</code></pre>

<p>model:</p>

<pre><code>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', ]
</code></pre>

<p>Full traceback of error:</p>

<blockquote>
  <p>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</p>
</blockquote>

<p>ImageField need to obtain file, not data. This solve the problem:</p>

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

python django