I am trying to get Django version 1.9 to delete the file corresponding to a FileField in my model when I remove the model. My first try was based on the delete signals as explained in another answer but that does not seem to work from Django 1.8 and onwards. Another answer pointed me in the direction of Django-cleanup but it does not work for me either (could it be that it uses the same approach internally?). I have also tried the post delete signal approach explained here but the method never triggered. So what is the new way of doing this, any approach that deletes the file when deleting the model is fine to me.
Asked
Active
Viewed 1,090 times
1
-
Your question is too broad but see if this answer helps http://stackoverflow.com/a/37127220/267540 – e4c5 May 10 '16 at 13:12
1 Answers
1
I went with the following workaround in my view:
@login_required
def deleteDataset(request, pk):
instance = DatasetModel.objects.defer('filecontent').get(pk=pk)
if request.method == 'POST':
path = instance.filecontent.path
instance.delete()
if os.path.isfile(path):
os.remove(path)
return redirect(main)
else:
return redirect(main)
But I still would like to find a better solution since I would prefer to keep the view as short as possible

jonalv
- 5,706
- 9
- 45
- 64