重写保存方法 - “镜像文件”对象没有属性“_committed”(override save me

2019-09-03 08:27发布

我重写保存方法像下面,和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)

有任何想法吗 ?

Answer 1:

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

解决我的问题..



Answer 2:

我最近发现了一个类似的错误,通过Django管理更新的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')

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



文章来源: override save method - 'ImageFile' object has no attribute '_committed'