覆盖保存方法 - 'ImageFile'对象没有属性'_committed'

时间:2013-05-15 10:51:02

标签: django django-models sorl-thumbnail

我覆盖了下面的save方法,get_thumbnails并使用sorl保存..

但是得到错误'ImageFile' object has no attribute '_committed'

class HotelPhotos(models.Model):
    hotel = models.ForeignKey(Hotel, related_name='photos')
    code = models.CharField(max_length=255)
    original = models.ImageField(upload_to="media")
    medium = models.ImageField(upload_to="media", null=True, editable=False)
    thumbnail = models.ImageField(upload_to="media", null=True, editable=False)

    def save(self, *args, **kwargs):

        super(HotelPhotos, self).save(*args, **kwargs)
        self.medium = get_thumbnail(self.original,
                                    '100x100',
                                    crop='center',
                                    quality=99)

        self.thumbnail = get_thumbnail(self.original,
                                       '50x50',
                                       crop='center',
                                       quality=99)

        super(HotelPhotos, self).save(*args, **kwargs)

有什么想法吗?

2 个答案:

答案 0 :(得分:11)

self.thumbnail = get_thumbnail(self.original,
                                   '50x50',
                                   crop='center',
                                   quality=99).url

解决了我的问题..

答案 1 :(得分:0)

我最近发现了类似的错误,这是在通过django admin更新ImageField的内容时发生的。

错误消息为: 'InMemoryUploadedFile'对象没有属性'_committed'

models.py:

class MyObject(models.Model):
    name = models.CharField(max_length=80, unique=True, db_index=True)
    slug = models.SlugField(max_length=80, unique=True, blank=False)
    some_image = ImageField(upload_to='uploads/some/')
    # ... deleted for brevity

这并没有影响到每一个模型,我把它缩小到这个:

admin.py:

class MyObjectAdmin(admin.ModelAdmin):
    # ... 
    def queryset(self, request):
        return super(ShipAdmin, self).queryset(request).only('name', 'slug')

解决方案是改变管理查询集,如下所示:

admin.py:

class MyObjectAdmin(admin.ModelAdmin):
    # ... 
    def queryset(self, request):
        return super(MyObjectAdmin, self).queryset(request).only('name', 'slug', 'some_image')

或者只是完全摆脱它,因为它不再是真正需要/相关的。