簡體   English   中英

在Django ImageField中上傳圖片

[英]Upload Image in Django ImageField

我嘗試使用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”編解碼器無法解碼位置0的字節0xff:無效的起始字節

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

完全回溯錯誤:

追溯(最近一次通話):文件“ D:\\ code \\ active \\ Python \\ Django \\ photo-hub \\ photo-hub \\ api \\ tests.py”,行66,位於test_photos_urls response = self.client.post(' / api / photos /',self.testPhoto,format =“ json”)文件“ C:\\ Users \\ User \\ AppData \\ Local \\ Programs \\ Python \\ Python35-32 \\ lib \\ site-packages \\ rest_framework \\ test.py” ,第172行,在發布路徑中,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“,第93行,在發布數據中,content_type = self._encode_data(數據,格式,content_type)文件“ C:\\ Users \\ User \\ AppData \\ Local \\ Programs \\ Python \\ Python35-32 \\ lib \\ _encode_data中的site-packages \\ rest_framework \\ test.py“行65 ret = renderer.render(data)文件” C:\\ Users \\ User \\ AppData \\ Local \\ Programs \\ Python \\ Python \\ Python35-32 \\ lib \\ site-packages渲染分隔符=分隔符中的\\ rest_framework \\ renderers.py“行103,轉儲中的文件” C:\\ Users \\ User \\ AppData \\ Local \\ Programs \\ Python \\ Python35-32 \\ lib \\ json__init __。py“,行237 s ** kw).encode(obj)文件“ C:\\ Users \\ User \\ AppData \\ Local \\ Programs \\ Python \\ Python35-32 \\ lib \\ json \\ encoder.py”,行198,在編碼塊中= self.iterencode (o,_one_shot = True)文件“ C:\\ Users \\ User \\ AppData \\ Local \\ Programs \\ Python \\ Python35-32 \\ lib \\ json \\ encoder.py”,行256,以iterencode返回_iterencode(o,0)文件“ C:\\ Users \\ User \\ AppData \\ Local \\ Programs \\ Python \\ Python35-32 \\ lib \\ site-packages \\ rest_framework \\ utils \\ encoders.py”,第54行,默認返回obj.decode('utf-8' )UnicodeDecodeError:'utf-8'編解碼器無法解碼位置0的字節0xff:無效的起始字節

ImageField需要獲取文件,而不是數據。 這樣可以解決問題:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM