首页 文章

将ImageField添加到模型会导致django中的异常

提问于
浏览
0

我已经创建了一个基本的CMS,我的下一步是添加图像上传功能 . 我在models.py中添加了一些行,之后因为UnicodeDecodeError我的模型没有验证:

Unhandled exception in thread started by 
    Traceback (most recent call last):
      File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 93, in w
    rapper
        fn(*args, **kwargs)
      File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.
    py", line 101, in inner_run
        self.validate(display_num_errors=True)
      File "C:\Python27\lib\site-packages\django\core\management\base.py", line 310,
     in validate
        num_errors = get_validation_errors(s, app)
      File "C:\Python27\lib\site-packages\django\core\management\validation.py", lin
    e 113, in get_validation_errors
        from django.utils.image import Image
      File "C:\Python27\lib\site-packages\django\utils\image.py", line 154, in 
        Image, _imaging, ImageFile = _detect_image_library()
      File "C:\Python27\lib\site-packages\django\utils\image.py", line 134, in _dete
    ct_image_library
        "imported: %s") % err
      File "C:\Python27\lib\site-packages\django\utils\functional.py", line 168, in
    __mod__
        return six.text_type(self) % rhs
    UnicodeDecodeError: 'ascii' codec can't decode byte 0xb3 in position 35: ordinal
     not in range(128)

这是我的models.py代码:

from django.db import models
    from django.contrib.auth.models import User

    ...

    class Photo(models.Model):
        title = models.CharField(max_length=255)
        upload_path = '/'
        photo = models.ImageField(upload_to=upload_path)
        def __unicode__(self):
            return self.title

我有Python 2.7.6,Django 1.6.1,MySQL-python-1.2.3 .

有人知道异常发生的原因吗?

2 回答

  • 1

    非常感谢,Odif Yltsaeb!有用!

    对像我这样的新手说明:

    1)转到https://pypi.python.org/pypi/Pillow/2.3.0并下载正确版本的枕头

    2)给你的models.py添加

    import PIL.Image as Image
    

    现在它应该工作!

  • 1

    你的问题可能是你的unicode方法并没有真正返回unicode .

    应该是这样的

    def __unicode__(self):
        return u'%s' % self.title
    

    如果你说这不能解决你的错误,那你就是对的 . 我去查看django代码,发现错误是在其他地方生成的 . 但是,你的unicode方法应该返回unicode而不是其他任何东西 .

    现在关于错误:django试图导入你的成像库 . 从我看到的,引发错误时出现错误产生错误 .

    您无法修复,但您可以检查是否已安装所需的映像库 . 失败的代码(并生成原始错误)是:

    import _imaging as PIL_imaging
    

    如何修复它(最有可能)是从计算机中删除PIL(如果你有的话)并安装PILLOW . 如果你仔细阅读1.6发行说明:https://docs.djangoproject.com/en/dev/releases/1.6/你可以看到,这个枕头现在是Django首选的图像处理库 .

    从链接页面复制:Pillow现在是与Django一起使用的首选图像处理库 . PIL正在等待弃用(支持在Django 1.8中删除) . 要升级,首先应卸载PIL,然后安装Pillow .

    去那里,按照卸载PIL和安装PILLOW的说明再次尝试您的代码 .

    Edit 您实际上不需要卸载/删除PIL . 删除它可能会导致像ubuntu这样的东西出现问题,其中gnome3桌面显然需要PIL ......

    /Edit

相关问题