带有upload_to的Django FileField在运行时确定 [英] Django FileField with upload_to determined at runtime

查看:27
本文介绍了带有upload_to的Django FileField在运行时确定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设置我的上传,以便如果用户 joe 上传文件,它会转到 MEDIA_ROOT/joe,而不是让每个人的文件都转到 MEDIA_ROOT.问题是我不知道如何在模型中定义它.这是它目前的样子:

I'm trying to set up my uploads so that if user joe uploads a file it goes to MEDIA_ROOT/joe as opposed to having everyone's files go to MEDIA_ROOT. The problem is I don't know how to define this in the model. Here is how it currently looks:

class Content(models.Model):
    name = models.CharField(max_length=200)
    user = models.ForeignKey(User)
    file = models.FileField(upload_to='.')

所以我想要的是而不是 '.'作为upload_to,让它成为用户名.

So what I want is instead of '.' as the upload_to, have it be the user's name.

我知道从 Django 1.0 开始,您可以定义自己的函数来处理 upload_to,但该函数也不知道用户是谁,所以我有点迷茫.

I understand that as of Django 1.0 you can define your own function to handle the upload_to but that function has no idea of who the user will be either so I'm a bit lost.

感谢您的帮助!

推荐答案

您可能已经阅读了 文档,所以这里有一个简单的例子来说明:

You've probably read the documentation, so here's an easy example to make it make sense:

def content_file_name(instance, filename):
    return '/'.join(['content', instance.user.username, filename])

class Content(models.Model):
    name = models.CharField(max_length=200)
    user = models.ForeignKey(User)
    file = models.FileField(upload_to=content_file_name)

如您所见,您甚至不需要使用给定的文件名 - 如果您愿意,也可以在您的 upload_to 可调用文件中覆盖它.

As you can see, you don't even need to use the filename given - you could override that in your upload_to callable too if you liked.

这篇关于带有upload_to的Django FileField在运行时确定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆