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