I have the following code to delete a file:
from django.db import models
from django import forms
import os
class Document(models.Model):
docfile = models.FileField(upload_to='documents/%Y/%m/%d')
def __unicode__(self):
return '%s' % (self.docfile.name)
def delete(self, *args, **kwargs):
os.rmdir(os.path.join(settings.MEDIA_ROOT, self.docfile.name))
super(Document,self).delete(*args,**kwargs)
It manages to delete the objects I ask it to in my views.py but when I reupload a file of the same name it seems as though the original file still exists since I'll get "output_1.txt" instead of "output.txt".
This is the code I use to delete:
def delete_matrix():
documents = Document.objects.all()
documents.delete()
Am I not deleting the file from the database? Any help would be appreciated.
Delete unused media files from Django projectPackage provides management command cleanup_unused_media for Django applications. You can remove all not used media files (files without references from any Django model with FileField or ImageField fields or their inheritances).
Topic: How to remove uploaded files (Read 78515 times) For the corresponding contribution, in the right-hand column “Actions”, click on "Upload" (see screenshot 1). On the next screen, click on the red button “Remove Uploaded File” to delete the file that has been uploaded for this contribution (see screenshot 2).
To delete the project you can delete the project folder. But this method is good only if you use SQLite as a database. If you use any other database like Postgresql with Django, you need to delete the database manually. Save this answer.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With