【问题标题】:What can be the filename of uploading location for ImageField?ImageField 的上传位置的文件名可以是什么?
【发布时间】:2018-03-08 19:01:48
【问题描述】:

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

我的问题是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。

【问题讨论】:

    标签: django django-models


    【解决方案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)
    

    【讨论】:

    • 我喜欢这个主意。如果 uuid.uuid4() 生成了以前的 id 怎么办?他们是否将先前生成的 id 存储到某个地方?如果不是,那只是随机整数,不是吗?
    • 这是基于许多参数的复合字段,您可以阅读更多uuid
    • 嗯.. 完全正确。我想为图像文件名生成真正的唯一 ID。 :(
    • nvm uuid 在生成随机文件名方面非常合法。酷的东西!谢谢
    • 很高兴为您提供帮助)
    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2011-12-01
      • 2017-06-08
      • 2019-08-28
      • 2013-02-14
      • 2011-04-28
      • 2014-01-24
      • 2010-11-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多