0

干草,我有一个模型可以保存 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/")

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

如果引发 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")
4

1 回答 1

1

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

您只需要将super调用移至设置代码之后。

顺便说一句,如果您要压倒一切save,我建议您这样做:

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

否则,在 Django 将参数传递给的任何情况下,您都会遇到异常save(我相信在少数情况下会出现异常,至少在管理员中是这样)。

于 2010-02-12T14:45:51.113 回答