当我从数据库中删除对象时,以前上传的图像保留在媒体目录中。我想将其自动删除。
这是我的模特:
class Door(models.Model) :
image = models.ImageField(upload_to=upload_location)
color = models.ForeignKey(Color, on_delete=models.CASCADE)
price = models.DecimalField(max_digits=10, decimal_places=2, default='119.99')
这是我的删除视图:
def door_delete(request, door_id) :
door = get_object_or_404(Door, id=door_id)
door.delete()
return redirect("/dashboard/doors")
我尝试在door.delete()
行door.image.delete()
之前插入,但据我所知,这还没有解决。
如果您知道答案,请帮助我。
答案 0 :(得分:0)
执行以下操作,
def door_delete(request, door_id):
door = get_object_or_404(Door, id=door_id)
if door.image:
door.image.delete()
door.delete()
return redirect("/dashboard/doors")
参考:How do I get Django Admin to delete files when I remove an object from the database/model?