A
A
Alexander Vinogradov2019-01-07 23:10:12
Django
Alexander Vinogradov, 2019-01-07 23:10:12

How to check links to a file before deleting?

There is a good example that deletes a file with the same name as the one being uploaded. An example is below.
This will get rid of duplicates, but the problem is that there is no check before deleting whether this file is referenced by another application or an entry in the table.
How to do it right?
Judging by the search, this is a long-standing question, but so far I have not found a harmonious solution, how not to produce duplicates, or how to clean unnecessary files later.

Example
class OverwriteStorage(FileSystemStorage):
    def get_available_name(self, name, max_length=None):
        if self.exists(name):
            os.remove(os.path.join(settings.MEDIA_ROOT, name))
        return name

class Images(models.Model):
    img = models.ImageField(storage=OverwriteStorage(), upload_to='photolog', verbose_name='Изображение')

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question