Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload an image from Django shell

I need to import a bunch of images into a Django app. I am testing in the shell but cannot get past this error when attempting to save the image:

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

The model:

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()

The steps to get to the error:

Open a 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)

Which gives the error above. I cannot figure out why an image is giving a unicodecodeerror... I got this far referring to "Upload" a file from django shell

More details:

Django 1.7, Python 3.3

Full traceback:

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
like image 282
Steve Avatar asked Jul 09 '14 23:07

Steve


1 Answers

I'd been bit by this before, so I feel you -- but as per my comment: replace the 'r' with 'rb' in the File() call, and it should work fine.

I should also add, for those who come upon this answer later, that this is an issue specific to Python3. Take a look at the SO link in Steve's comment for a fuller explanation of the difference in File() between p2 and p3.

like image 68
MBrizzle Avatar answered Sep 28 '22 03:09

MBrizzle