从Django Shell上传图片

史蒂夫

我需要将一堆图像导入Django应用。我正在外壳中进行测试,但是尝试保存图像时无法克服此错误:

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外壳。

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。。。我到此为止指的是从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
MBrizzle

我想这个已经有点过,所以我觉得你-但按我的意见:更换'r''rb'的文件()调用,它应该工作的罚款。

对于以后提出这个答案的人,我还应该补充一点,这是Python3特有的问题。请看一下史蒂夫评论中的SO链接,以更全面地解释File()p2和p3之间的区别

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章