我有以下信号可以从我的硬盘中删除旧的 postcover 和 postcover_tn(缩略图)。如果我只是通过表单删除文件并调用 save() ,这工作正常,但是如果我想用新文件覆盖旧文件,我上传的旧文件仍在我的 fs 上,知道如何解决这个问题吗? :
signals.py
@receiver(models.signals.pre_save, sender=Post)
def post_auto_delete_files_on_change(sender, instance, **kwargs):
"""
Deletes old file from filesystem
when corresponding object is updated
with new file.
"""
if not instance.pk:
return False
try:
old_postcover = sender.objects.get(pk=instance.pk).postcover
old_postcover_tn = sender.objects.get(pk=instance.pk).postcover_tn
except sender.DoesNotExist:
return False
if not old_postcover:
return
new_postcover = instance.postcover
if not old_postcover == new_postcover:
if os.path.isfile(old_postcover.path):
os.remove(old_postcover.path)
new_postcover_tn = instance.postcover_tn
if not old_postcover_tn == new_postcover_tn:
if os.path.isfile(old_postcover.path):
os.remove(old_postcover.path)
postcover_tn 是在 Post 的 save() 上生成的,如果你想知道的话。
四季花海
白猪掌柜的
相关分类