1

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)

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

7 Comments

ok so Picture.objects.get(self.get_object()).file.delete() it's correct?
I imagine that you are using class based views. If so, then self.get_object() returns an object (Picture) in question. So to delete the file, then you can do self.get_object().file.delete().
ok sry but I want to delete in database reference and in the folder
What do you mean by that? Do you want to remove the Picture instance which will also delete the file associated with that picture?
i want to delete the file ( HDD file) and the object in the database
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.