django-storages + private S3 bucket - 如何让用户名成为文件夹名称?

django-storages + private S3 bucket - How can I make a username the folder name?

我正在使用 django-storages 和私有 S3 存储桶来存储用户上传的内容。我想要以下文件夹结构:

/uploads/someuser321/20190112-123456/

我显然知道如何做时间戳(2019-01-12 at 12:34:56),但是如何将用户的用户名放入路径中?我的模型目前看起来像这样:

user_file = models.FileField(
    upload_to="uploads", 
    storage=PrivateMediaStorage(), 
    null=True, blank=True)

我可以为 datetime/timestamp 添加一个 f-string。我明白这一点,我知道该怎么做。但是我怎样才能将用户的用户名也添加为文件夹呢?我需要以某种方式从视图中访问它,以便我知道 request.user 是谁,但我该怎么做呢?

您需要在 upload_to 中进行函数调用。这是一个可以为您提供路径的函数:

def get_file_path(instance, filename):
    today = localtime(now()).date()
    return '{0}/uploads/{1}/{2}'.format(instance.user.username, today.strftime('%Y/%m/%d'), filename)

然后你需要在你的模型中这样调用它:

user_file = models.FileField(
    upload_to=get_file_path, 
    storage=PrivateMediaStorage(), 
    null=True, blank=True)

您需要修复 return 语句以获得所需的格式,但这样就可以了。 Django 会自动将一个实例传递给您的函数和文件名。

希望对您有所帮助!