首页 > 解决方案 > django-storages + private S3 bucket - 如何将用户名设为文件夹名称?

问题描述

我正在使用 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)

我可以为日期时间/时间戳添加一个 f 字符串。我明白这一点,我知道该怎么做。但是如何将用户的用户名也添加为文件夹?我需要以某种方式从视图中访问它,以便我知道 request.user 是谁,但我该怎么做呢?

标签: djangoamazon-s3django-modelsboto3python-django-storages

解决方案


您需要在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 会自动将实例传递给您的函数和文件名。

我希望这会有所帮助!


推荐阅读