I would like to delete file associated to a file-field
But it doesn’t work.
Can you fix it please?
Models.py
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
Views.py
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)
You can remove file objects using the
FileFieldapi: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.