相关疑难解决方法(0)

Django - 获取上传的文件类型/ mimetype

有没有办法在覆盖模型保存方法时获取上传文件的内容类型?我试过这个:

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)

编辑:我希望能够将内容类型保存到数据库,所以在保存实际完成之前我需要它:)

django

16
推荐指数
3
解决办法
3万
查看次数

如何在保存前使用PIL调整新上传的图像大小?

我想以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)

django django-models python-imaging-library

16
推荐指数
2
解决办法
2万
查看次数