django - 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 是谁,但我该怎么做呢?
解决方案
您需要在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 会自动将实例传递给您的函数和文件名。
我希望这会有所帮助!
推荐阅读
- php - 在浏览器中强制 404
- xamarin - 为 Xamarin Forms 应用程序创建 MSI 安装程序
- javascript - 如何断言所有 $ReadOnlyArray 成员都属于某种类型?
- javascript - 在 vue.js 应用程序中设置视口元标记
- php - 在 Laravel 项目中上传视频
- pandas - Pandas,isin,列表列
- java - 根据 Collection.toArray(T[] array) 合同将 Java 流转换为数组
- python - 条件语句 Python Apache Beam 管道
- python - 使用 selenium 执行 python 脚本时出错
- python - 如何从文本文件中解析电子邮件和密码(Python)