【问题标题】:Django image field throws TypeErrorDjango 图像字段抛出 TypeError
【发布时间】:2013-07-05 10:53:25
【问题描述】:

我正在使用 django 编写一个简单的网站来显示一些图片。在我的模型中,我定义了一个图像模型和一个类别模型,以允许我对每个图像进行分类:

class Image(models.Model):
    title = models.CharField(max_length=200)
    image = models.ImageField(upload_to='images')
    tags = models.ManyToManyField(Category)

我想使用 django 的内置 ImageField 字段 django.db.models.ImageField 附加实际的图像字段,该字段又使用 Python 图像库。我可以很好地定义我的模型,但是当我尝试通过内置管理站点添加图像时,点击保存时出现以下错误: TypeError: 'ImageFieldFile' object has no attribute '__getitem__' 我不明白为什么我会看到这个错误,因为我从不要求 getitem' 属性,并且我的所有其他字段都可以正常工作 - 只有 ImageField 会导致 TypeError。有任何想法吗?这可能是我的 PIL 安装的问题吗?我在 Mac 上,一开始安装 PIL 时遇到了一些小困难,但现在它似乎工作正常。谢谢!

【问题讨论】:

    标签: python django python-imaging-library


    【解决方案1】:

    我在这门课上遇到了类似的问题:

    class Photo(models.Model):
        image_location = models.ImageField(upload_to='pix/%Y/%m/%d')
        caption = models.CharField(max_length=100)
    
        object = Manager()
    

    您看到错误可能是因为您正在返回模型对象(例如:照片对象):

    #returning model object(eg: Photo object)
    def __unicode__(self):
        return self.image_location
    

    而不是 unicode 字符串(例如:/Path/to/my/pix):

    #returning unicode string instead of model object(eg: /Path/to/my/pix)
    def __unicode__(self):
        return unicode(self.image_location)
    

    这是帮助我的 StackOverflow 答案的链接:TypeError 'x' object has no attribute '__getitem__'

    【讨论】:

      【解决方案2】:

      实现__getitem__ 方法的类允许您在其上使用数组索引。所以MyClass[4](大致)相当于MyClass.__getitem__[4].

      确保您不会意外尝试在 ImageField/ImageFieldFile 上使用数组索引器。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-07-09
        • 1970-01-01
        • 2021-03-10
        • 1970-01-01
        • 2021-11-21
        • 1970-01-01
        • 2013-07-24
        相关资源
        最近更新 更多