views:

352

answers:

3

What's the best way to rename photos with a unique filename on the server as they are uploaded, using django? I want to make sure each name is used only once. Are there any pinax apps that can do this, perhaps with GUID?

A: 

How about concatenating the filename with the date / time the photo was uploaded and then using hashlib to create a message digest? That should give you unique filenames.

Alternatively you could re-use a neat little snippet which creates unique filenames and then use the full path to that file as the input to your hash call. That gives you unique constant length strings which you can map to your files.

Jon Cage
but,how to do the same name when the same time ?
zjm1126
You could add the amount of free disk space into the hash string - that should always change when you upload a new file.
Jon Cage
@zjm1126 @Jon Cage you could invent all sorts of ways of making it more likely to be unique and such but there will basically always be some sort of probability of collisions and the idea is just to reduce that probability to an acceptable amount and then handle when it does happen
Daniel DiPaolo
Indeed. The snippet I linked to really would be unique though; the filesystem would garauntee that only one file could be created with the same name. So creating a has on the full path of that should be pretty good.
Jon Cage
A: 

If you're using a file field to save the files, it will automatically give then a unique name. So, for example, if you save one file "test.jpg" and then another file, "test.jpg" to your server, the first will be called test.jpg, and the second will be called test_1.jpg.

mlissner
+5  A: 

Use uuid. To tie that into your model see Django documentation for FileField upload_to.

For example in your models.py define the following function:

import uuid
def get_file_path(instance, filename):
    ext = filename.split('.')[-1]
    filename = "%s.%s" % (uuid.uuid4(), ext)
    return os.path.join('uploads/logos', filename)

Then, when defining your FileField/ImageField, specify get_file_path as the upload_to value.

file = models.FileField(upload_to=get_logo_path,
                        null=True,
                        blank=True,
                        verbose_name=_(u'Contact list'))
Nathan