ImageField在IOError异常时没有失败

时间:2010-02-12 14:20:09

标签: python django ioerror imagefield

Hay,我有一个可以保存2张图像的模型

class Picture(models.Model):
    picture = models.ImageField(upload_to=make_filename)
    thumbnail = models.ImageField(upload_to=make_thumb_filename)
    car = models.ForeignKey('Car')
    created_on = models.DateField(auto_now_add=True)
    updated_on = models.DateField(auto_now=True)

    def save(self):
        super(Picture, self).save()
        size = 200, 200
        filename = str(self.thumbnail.path)
        image = Image.open(filename)
        image.thumbnail(size, Image.ANTIALIAS)
        image.save(filename)

正如你所看到的,我已经覆盖了save()方法 我的观点是我有一个简单的尝试,除了块,它检查IOErrors(如果上传了图像以外的文件则会引发)

def upload(request):
    car = Car.objects.get(pk=1)
    try:
        picture = Picture(picture=request.FILES['image'], thumbnail=request.FILES['image'], car=car)
        picture.save()
    except IOError:
        return HttpResponseRedirect("/test/")

但是,引发了异常,但文件仍然写入服务器(和db)

如果引发IOError,如何确保文件不会被写入的任何想法?

修改

通过编写自定义方法

进行修复
def is_accectable_file(filename):
    extension = filename.split('.')[-1]
    acceptable_filetypes = ['jpeg','jpeg','gif','png']
    if extension in acceptable_filetypes:
        return True
    else:
        return False

然后退出我的模型

class Picture(models.Model):
    picture = models.ImageField(upload_to=make_filename)
    thumbnail = models.ImageField(upload_to=make_thumb_filename)
    car = models.ForeignKey('Car')
    created_on = models.DateField(auto_now_add=True)
    updated_on = models.DateField(auto_now=True)

    def save(self, *args, **kwargs):
        if is_accectable_file(self.picture.name):
            super(Picture, self).save(*args,**kwargs)
            size = 200, 200
            filename = str(self.thumbnail.path)
            image = Image.open(filename)
            image.thumbnail(size, Image.ANTIALIAS)
            image.save(filename)
            return True
        else:
            return False

和我的观点

def upload(request):
    car = Car.objects.get(pk=1)
    try:
        picture = Picture(picture=request.FILES['image'], thumbnail=request.FILES['image'], car=car)
        if picture.save():
            return HttpResponse("fine")
        else:
            return HttpResponse("invalid type")
    except:
        return HttpResponse("no file")

1 个答案:

答案 0 :(得分:1)

在调用super(Picture,self).save()方法之后,(我假设)抛出IOError的代码正在运行。因此,即使抛出异常,图像也会写入数据库。

您只需要在设置代码后移动super来电。

顺便说一句,如果你要覆盖save,我建议按以下方式进行:

def save(self,*args,**kwargs):
    ...
    super(Picture, self).save(*args,**kwargs)

否则,在Django将参数传递给save的任何情况下,你都会得到一个例外(我相信有一些例子,至少在管理员中)。