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

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

问题描述

我正在尝试设置我的上传,以便如果用户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 callable中覆盖。

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.

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

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