我正在使用 django-storages 和私有(private) S3 存储桶来存储用户上传的内容。我想要以下文件夹结构:
/uploads/someuser321/20190112-123456/
我显然知道如何做时间戳(2019-01-12 12:34:56),但是如何将用户的用户名放入路径中?我的模型目前如下所示:
user_file = models.FileField(
upload_to="uploads",
storage=PrivateMediaStorage(),
null=True, blank=True)
我可以为日期时间/时间戳添加一个 f 字符串。我明白这一点并且我知道该怎么做。但是如何将用户的用户名也添加为文件夹呢?我需要以某种方式从 View 中访问它,以便我知道 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 会自动将实例和文件名传递给您的函数。
希望对您有所帮助!
关于django-storages + 私有(private) S3 存储桶 - 如何将用户名设为文件夹名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54641323/