2017-09-27 731 views
1

每当我创建Cloth型号与cloth_image,图像上传到upload_location可以为ImageField上传位置的文件名是什么?

我的问题是instance.id返回None,因为该实例尚未创建。 什么是ImageField的最佳上传位置?

def upload_location(instance, filename): 
    new_id = instance.id 
    ext = filename.split('.')[-1] 
    return "clothes/%s/%s.%s" % (instance.user.id, new_id, ext) # <- Right Here! 

class Cloth(models.Model): 
    cloth_image = models.ImageField(upload_to=upload_location, 
           null=True, 
           blank=True) 

我正在使用AWS S3。

回答

1

,我认为你可以使用uuid它,例如

import uuid 
import os 

def get_file_path(instance, filename): 
    base_dir = 'clothes' 
    user.id = str(instance.user.id) 
    ext = filename.split('.')[-1] 
    filename = "%s.%s" % (uuid.uuid4(), ext) 
    return os.path.join(base_dir, user_id, filename) 
+0

我喜欢这个主意。如果uuid.uuid4()生成以前的ID呢?他们是否将以前生成的ID存储到某个地方?如果不是,它只是随机整数,不是吗? –

+0

这是基于许多参数的综合字段,你可以阅读更多[uuid](https://docs.python.org/2/library/uuid.html) –

+0

嗯..确切地说。我想为图像文件名生成REAL唯一ID。 :( –

1

只需使用文件名而不是id,例如

os.path.join('clothes', instance.user.id, filename) 

不要担心,如果文件名已经存在,Django会自动在末尾附加随机字符串,以避免文件替换。

如果你想唯一的文件名
相关问题