tags:

views:

163

answers:

3

I need to generate name of uploaded image with mask

images/{{ uploaded_image.id }}.jpg

I think the best way to do this is *FileField.upload_to* property, but it is written Here:

In most cases, this object will not have been saved to the database yet, so if it uses the default AutoField, it might not yet have a value for its primary key field.

May be in my case it will be better to rename file after saving object in save() method?

+1  A: 

To avoid concurrency issues, you will need to store your object to the database before you determine the filename (because even if you get the next incremental id, which is possible, it may change while you save the file.) So store the object and then rename the file.

Blixt
+2  A: 

What I do is give upload_to a function, then assign a UUID is the function for it to save to:

import uuid

def get_upload_to(instance, filename):
    instance.uuid = uuid.uuid4().hex
    return 'blah/%s/%s' % (instance.uuid, filename)

class Photo(models.Model):
    file = models.FileField(max_length=200,upload_to=get_upload_to)
    uuid = models.CharField(max_length=32)
Todd Gardner
Maybe "uuid.uuid4().hex" ?
Glader
@Glader - thanks, cleaned it up a bit
Todd Gardner
A: 

Thanks, Blixt and Todd! I choose better solution for my issue:

import time
class Image(models.Model):
    def _get_upload_to(instance, filename):
        return 'images/%f.jpg' % time.time()

    original = models.ImageField(upload_to=_get_upload_to, ....)

It is guarantees that every filename will be unique in the same directory. In my case I need only jpg files, so in other cases it possible to substitute original extension

ramusus
As a warning, you could have problems if you submit images too quickly with that.
Todd Gardner
time.time() returns float value - seconds and fraction of seconds like "images/1245720125.783708.jpg". I think situation with 2 equal names never will be in this case.
ramusus