S
S
Stanislav Shabalin2020-08-27 18:03:56
Django
Stanislav Shabalin, 2020-08-27 18:03:56

How to prevent duplication when saving images in uploads?

There is a model in Django:

class Image(models.Model):
    title = models.CharField(max_length=200)
    image = models.ImageField(upload_to='uploads/')

    def __str__(self):
        return self.title


The essence of the problem is as follows:
If the photo is in uploads, and I need to attach it to the post, then after selecting and then saving, the file is duplicated. How can I check for the existence of such a file and cancel duplication if it already exists on the server? Tell me, pliz, how to be?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2020-08-27
@Starck43

Pass to the upload_to parameter a reference to a function that calculates the md5 hash of the file's contents and generates the appropriate name for it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question