Reputation: 333
I would like to delete file associated to a file-field But it doesn't work.
Can you fix it please?
class Picture(models.Model):
file = models.FileField(upload_to="pictures")
slug = models.SlugField(max_length=50, blank=True)
def __unicode__(self):
return self.file
def getFileName(self):
return self.docfile.name
def delete(self, request, *args, **kwargs):
"""
This does not actually delete the file, only the database record.
"""
self.object = self.get_object()
path = "/media/pictures" + '/' + self.object.name
#path = MEDIA_ROOT + '/' + self.object.name
#path = MEDIA_ROOT + '/' + self.object.getFileName()
self.object.delete()
os.remove(path)
Upvotes: 1
Views: 1678
Reputation: 27861
You can remove file objects using the FileField
api:
Picture.objects.get(...).file.delete()
That will use storage API to remove the file. The advantage of that is that this approach works even if you want to switch your storage to different system such as Amazon S3.
Upvotes: 3