最佳答案
我在姜戈建一个网络应用。我有一个上传文件的模型,但我不能删除该文件。这是我的代码:
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)
然后,在 python manage.py shell
中我这样做:
song = Song.objects.get(pk=1)
song.delete()
它从数据库中删除记录,但不删除服务器上的文件。 我还能试什么?
谢谢!