gpt4 book ai didi

python - 从 Django shell 上传图像

转载 作者:太空狗 更新时间:2023-10-29 20:39:37 31 4
gpt4 key购买 nike

我需要将一堆图像导入 Django 应用程序。我正在 shell 中进行测试,但在尝试保存图像时无法解决此错误:

File "/lib/python3.3/codecs.py", line 301, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0:
invalid start byte

模型:

import uuid
from django.db import models
from taggit.managers import TaggableManager
import os

def generate_filename(instance, filename):
f, ext = os.path.splitext(filename)
name = uuid.uuid4().hex
return 'images/%s%s' % (name, ext)

class StudyImage(models.Model):

pic = models.ImageField(upload_to=generate_filename)
upload_date = models.DateTimeField(auto_now_add=True)
tags = TaggableManager()

出现错误的步骤:

打开一个 django shell。

import uuid
import os
from app import models

p = File(open('/home/image001.png', 'r'))
a = models.StudyImage(pic=p)
a.pic.save('test.jpg',p)

这给出了上面的错误。我无法弄清楚为什么图像给出了 unicodecodeerror ...我到目前为止指的是 "Upload" a file from django shell

更多详情:

Django 1.7,Python 3.3

完整回溯:

Traceback (most recent call last):<br>
File "<input>", line 1, in <module><br>
File "/home/s/Pycharm/flf/venv/lib/python3.3/site-
packages/django/db/models/fields/files.py", line 89, in save
self.name = self.storage.save(name, content)
File "/home/s/Pycharm/flf/venv/lib/python3.3/site-
packages/django/core/files/storage.py", line 51, in save
name = self._save(name, content)
File "/home/s/Pycharm/flf/venv/lib/python3.3/site-
packages/django/core/files/storage.py", line 224, in _save
for chunk in content.chunks():
File "/home/s/Pycharm/flf/venv/lib/python3.3/site-packages/django/core/files/base.py",
line 77, in chunks
data = self.read(chunk_size)
File "/home/s/Pycharm/flf/venv/lib/python3.3/codecs.py", line 301, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte

最佳答案

我以前被这个问题困扰过,所以我感觉到你——但根据我的评论:将文件中的 'r' 替换为 'rb' () 调用,它应该可以正常工作。

我还应该补充一点,对于那些后来遇到这个答案的人来说,这是一个特定于 Python3 的问题。查看 Steve 评论中的 SO 链接,以更全面地解释 p2 和 p3 之间 File() 的区别。

关于python - 从 Django shell 上传图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24665259/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com