从Django shell上传图片

时间:2014-07-09 23:26:42

标签: python django file shell

我需要将一堆图像导入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

1 个答案:

答案 0 :(得分:18)

我以前对此感到满意,所以我觉得你 - 但根据我的评论:在File()调用中用'r'替换'rb',它应该可以正常工作。

对于那些稍后得出这个答案的人,我还应该补充一点,这是Python3特有的问题。请查看Steve评论中的SO链接,以更全面地解释p2和p3之间File()的差异。