我正在用Django构建一个web应用程序。我有一个上传文件的模型,但我不能删除该文件。下面是我的代码:
class Song(models.Model):
name = models.CharField(blank=True, max_length=100)
author = models.ForeignKey(User, to_field='id', related_name="id_user2")
song = models.FileField(upload_to='/songs/')
image = models.ImageField(upload_to='/pictures/', blank=True)
date_upload = models.DateField(auto_now_add=True)
def delete(self, *args, **kwargs):
# You have to prepare what you need before delete the model
storage, path = self.song.storage, self.song.path
# Delete the model before the file
super(Song, self).delete(*args, **kwargs)
# Delete the file after the model
storage.delete(path)
然后,在
我这样做:
song = Song.objects.get(pk=1)
song.delete()
它会从数据库中删除记录,但不会删除服务器上的文件。我还能尝试什么?
谢谢!
发布于 2015-03-11 20:14:47
尝试django-清理,当您移除模型时,它会自动调用FileField上的delete方法。
pip install django-cleanup
settings.py
INSTALLED_APPS = (
...
'django_cleanup', # should go after your apps
)
https://stackoverflow.com/questions/16041232
复制相似问题