有没有办法在覆盖模型保存方法时获取上传文件的内容类型?我试过这个:
def save(self):
print(self.file.content_type)
super(Media, self).save()
Run Code Online (Sandbox Code Playgroud)
但它没有用.在此示例中,self.file是model.FileField:
file = models.FileField(upload_to='uploads/%m-%Y/')
Run Code Online (Sandbox Code Playgroud)
编辑:我希望能够将内容类型保存到数据库,所以在保存实际完成之前我需要它:)
我想以800px的高度和宽度调整新图像的大小并保存它们.应用程序不得存储真实图像.有帮助吗?
这是我的代码,它保存原始图像,而不是调整大小的照片:
models.py:
class Photo(models.Model):
photo = models.ImageField(upload_to='photos/default/')
def save(self):
if not self.id and not self.photo:
return
super(Photo, self).save()
image = Image.open(self.photo)
(width, height) = image.size
"Max width and height 800"
if (800 / width < 800 / height):
factor = 800 / height
else:
factor = 800 / width
size = ( width / factor, height / factor)
image.resize(size, Image.ANTIALIAS)
image.save(self.photo.path)
Run Code Online (Sandbox Code Playgroud)