Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在django中从数据库中删除图像_Python_Django_Database_Python Imaging Library - Fatal编程技术网

Python 如何在django中从数据库中删除图像

Python 如何在django中从数据库中删除图像,python,django,database,python-imaging-library,Python,Django,Database,Python Imaging Library,我有一个数据库,其中包含作为文章的图像,并希望该功能,以便在删除文章后删除数据库中的图像。我正在使用枕头模块来处理数据库中的图像。我有办法做到吗 在my models.py中,这是我用来保存图像的代码。以防万一 def save(self): super().save() img = Image.open(self.picture.path) width, height = img.size ratio = width/height if img.heig

我有一个数据库,其中包含作为文章的图像,并希望该功能,以便在删除文章后删除数据库中的图像。我正在使用枕头模块来处理数据库中的图像。我有办法做到吗

在my models.py中,这是我用来保存图像的代码。以防万一

def save(self):
    super().save()
    img = Image.open(self.picture.path)
    width, height = img.size
    ratio = width/height
    if img.height > 500:
        outputsize = (500, (height/ratio))
        img.thumbnail(outputsize)
        img.save(self.picture.path)

非常感谢

我有两个可能有效的解决方案:

def delete(self,*args,**kwargs):
#在删除模型之前,您必须准备好所需的内容
存储,路径=self.image.storage,self.image.path
#删除文件之前的模型
超级(个人资料,自我)。删除(*args,**kwargs)
#删除模型后的文件
存储。删除(路径)
将其添加到要从中删除图像的模型中

Model.objects.get(id=obj_id).photo.delete(save=True)
将obj_id、照片和模型替换为您认为必要的实例


不过,在其他线程上还有更多的解决方案。查一下“Django delete filefield”,如果我的建议不起作用,你会找到更长的解决方案。

好吧,因为到目前为止最好的方法是你可以先做

pip安装django清理

然后在settings.py中添加

INSTALLED_APPS = (
 ...
'django_cleanup', # should go after your apps)

这就行了

不,两个模型都不起作用,但有一个更简单的方法可以做到,我们应该“pip install django cleanup”并将其添加到已安装的应用程序中。非常感谢您在尝试这个问题时花费的时间和精力