ImageField上传位置的文件名是什么?

时间:2017-09-27 10:18:57

标签: django django-models

每当我使用Cloth创建cloth_image模型时,图片都会上传到upload_location

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

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。

2 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分: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)
相关问题