从Django shell上传图片

Ste*_*eve 8 python django shell file

我需要将一堆图像导入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
Run Code Online (Sandbox Code Playgroud)

该模型:

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()
Run Code Online (Sandbox Code Playgroud)

获取错误的步骤:

打开一个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)
Run Code Online (Sandbox Code Playgroud)

这给出了上面的错误.我无法弄清楚为什么一个图像给出了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
Run Code Online (Sandbox Code Playgroud)

MBr*_*zle 18

我之前一直都是这样,所以我觉得你 - 但根据我的评论:在File()调用中替换'r'with 'rb',它应该可以正常工作.

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