Django图像字段引发TypeError [英] Django image field throws TypeError
问题描述
我正在使用django编写一个简单的网站来显示一些图片.在我的模型中,我定义了一个图像模型和一个类别模型,以便我可以对每个图像进行分类:
I'm writing a simple website using django to display some pictures. In my models, I've defined an image model, and a category model to allow me to categorize each image:
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 Imaging Library.我可以很好地定义模型,但是当我尝试通过内置的管理站点添加图像时,单击保存会出现以下错误:
TypeError: 'ImageFieldFile' object has no attribute '__getitem__'
我不明白为什么会看到此错误,因为我从不要求
getitem "属性,其他所有字段都可以正常工作-只是ImageField导致TypeError.有任何想法吗?我的PIL安装是否可能有问题?我在Mac上,一开始安装PIL时遇到了一些小麻烦,但现在看来工作正常.谢谢!
I'd like to attach the actual image field using django's built in ImageField field django.db.models.ImageField
which in turn uses the Python Imaging Library. I can define my models fine, but when I attempt to add an Image through the built-in admin site, I get the following error upon hitting save:
TypeError: 'ImageFieldFile' object has no attribute '__getitem__'
I don't understand why I'm seeing this error, as I never ask for the
getitem' atribute, and all of my other fields work fine – it's only the ImageField that causes the TypeError. Any Ideas? Is this possibly an issue with my PIL install? I am on a Mac, and had some minor difficulty installing PIL in the first place, but it seems to work fine now. Thanks!
推荐答案
我遇到了与此类类似的问题:
I ran into a similar issue with this class:
class Photo(models.Model):
image_location = models.ImageField(upload_to='pix/%Y/%m/%d')
caption = models.CharField(max_length=100)
object = Manager()
您看到此错误的原因可能是因为您要返回模型对象(例如:照片对象):
You're seeing the error possibly because you're returning a model object (eg: Photo object):
#returning model object(eg: Photo object)
def __unicode__(self):
return self.image_location
代替unicode字符串(例如:/Path/to/my/pix):
Instead of a unicode string (eg: /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 '对象没有属性'__getitem__'
This is the link to the StackOverflow answer that helped me: TypeError 'x' object has no attribute '__getitem__'
这篇关于Django图像字段引发TypeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!