Deleting uploaded files in Django
Your problem is that you are overriding the delete()
method on the model but you are calling the delete
method on the QuerySet
returned by the default manager (Documents.object.all().delete()
). These are 2 separate methods so there are 2 ways of fixing this.
1.In the delete
method of the model, replace the line
os.rmdir(os.path.join(settings.MEDIA_ROOT, self.docfile.name))
by
os.remove(os.path.join(settings.MEDIA_ROOT, self.docfile.name))
AND, call the delete method for each object separately. Replace
Document.objects.all().delete()
with
documents = Document.objects.all()
for document in documents:
document.delete()
2.Replace the default manager to return a custom QuerySet
which overrides the delete()
method. This is explained in Overriding QuerySet.delete()
in Django