在Django ImageField

时间:2016-10-13 06:52:35

标签: python django

我尝试使用ImageField测试我的模型,为此,我以二进制模式读取.jpg文件并保存在模型中。我在StackOverflow中发现了很多问题,但似乎没有什么对我有用。

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')

错误:

  

UnicodeDecodeError:' utf-8'编解码器不能将字节0xff解码到位   0:无效的起始字节

test.py

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)

串行器:

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',)

视图:

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)

模型:

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', ]

完整的错误追溯:

  

Traceback(最近一次调用最后一次):文件   " D:\ code \ active \ Python \ Django \ photo-hub \ photo-hub \ api \ tests.py",line   66,在test_photos_urls中       response = self.client.post(' / api / photos /',self.testPhoto,format =" json")文件   " C:\用户\用户\应用程序数据\本地\程序\的Python \ Python35-32 \ lib中\站点包\ rest_framework \ test.py&#34 ;,   第172行,在帖子中       path,data = data,format = format,content_type = content_type,** extra)文件" C:\ Users \ User \ AppData \ Local \ Programs \ Python \ Python35-32 \ lib \ site-packages \ rest_framework \ test.py&#34 ;,   第93行,在帖子中       data,content_type = self._encode_data(data,format,content_type)文件   " C:\用户\用户\应用程序数据\本地\程序\的Python \ Python35-32 \ lib中\站点包\ rest_framework \ test.py&#34 ;,   第65行,在_encode_data中       ret = renderer.render(data)File" C:\ Users \ User \ AppData \ Local \ Programs \ Python \ Python35-32 \ lib \ site-packages \ rest_framework \ renderers.py",   103行,渲染       separators = separators文件" C:\ Users \ User \ AppData \ Local \ Programs \ Python \ Python35-32 \ lib \ json__init __。py",   第237行,在转储中       ** kw).encode(obj)File" C:\ Users \ User \ AppData \ Local \ Programs \ Python \ Python35-32 \ lib \ json \ encoder.py",   第198行,编码       chunks = self.iterencode(o,_ one_shot = True)文件" C:\ Users \ User \ AppData \ Local \ Programs \ Python \ Python35-32 \ lib \ json \ encoder.py",   第256行,在iterencode中       return _iterencode(o,0)File" C:\ Users \ User \ AppData \ Local \ Programs \ Python \ Python35-32 \ lib \ site-packages \ rest_framework \ utils \ _cnysrs.py",   第54行,默认情况下       return obj.decode(' utf-8')UnicodeDecodeError:' utf-8'编解码器不能解码位置0中的字节0xff:无效的起始字节

1 个答案:

答案 0 :(得分:0)

ImageField需要获取文件,而不是数据。这解决了这个问题:

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