Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can I delete an image each time I delete the instance asociated with it? #16

Closed
sgaseretto opened this issue May 9, 2018 · 4 comments

Comments

@sgaseretto
Copy link

If I have a model that has an ImageField as an attribute, how can I delete the image each time I do model_instance.delete()? I've seen that there is the deleteorphanedmedia command, but I don't understand how to use it each time I delete something that has an image.
What extra steps do I need to add to achieve this so I stop having orphan images?

@klis87
Copy link
Owner

klis87 commented May 9, 2018

This is just how Django works for media files, it works the same for all storages, this is by design. If you dont like it, you can use Django signals or you can delete given file in overwritten delete model method, pls see Django docs for more info

@sgaseretto
Copy link
Author

sgaseretto commented May 9, 2018

I understand. Is there a way to at least get the public_id from the image and delete it doing something like
cloudinary.uploader.destroy(custommodel.image.public_id,invalidate=True)

@klis87
Copy link
Owner

klis87 commented May 9, 2018

Field file actually has delete method, so you should be able to do this: model_instance.file_field.delete() before deleting the whole model instance. (https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.fields.files.FieldFile.delete) Also, you should be able to do this: storageInstance.delete(model_instance.file_field.name).

You should never do sth like cloudinary.uploader.destroy(custommodel.image.public_id,invalidate=True), thats why you use storage from this package which does those low level things for you :). See https://github.com/klis87/django-cloudinary-storage/blob/master/cloudinary_storage/storage.py#L73

@sgaseretto
Copy link
Author

sgaseretto commented May 10, 2018

That is what I was looking for!
I did the following

    storage_instace.delete(name=model_instance.file.name)
    model_instance.delete()

and it works great. Thanks a lot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants