Django模型与FileField - 动态'upload_to'参数 [英] Django model with FileField -- dynamic 'upload_to' argument
问题描述
我正在使用FileField的模型来处理文件上传。现在可以成功上传文件。然而,我想要做的还有一个小小的改进,就是为用户创建用户名的文件夹。
这是我试过的代码<
$ b pre $ class UserFiles(models.Model):
user = models.OneToOneField(User)
file = models。 FileField(upload_to ='files / users / user.username /%Y_%m_%d /')
这将给出'user.username'的文件夹,而不是'John'(一个用户名的例子)
我也尝试过其他方式,如 files / users /%user.username /%Y_%m_%d /
,但它不会给具有用户名的文件夹。不确定语法应该如何,或者是否可行。
你可以给出一些建议吗?
非常感谢您的帮助和解释。
代替字符串尝试传递函数:
def generate_filename(self,filename):
url =files / users /%s /%s% .user.username,filename)
return url
class UserFiles(models.Model):
user = models.OneToOneField(User)
file = models.FileField (upload_to = generate_filename)
I am using the model with FileField to deal with file uploading. Now the files can be uploaded successfully. However, there is one more small improvement I want to make, which is to create folder for the user with the username.
Here is the code I've tried
class UserFiles(models.Model):
user = models.OneToOneField(User)
file = models.FileField(upload_to='files/users/user.username/%Y_%m_%d/')
this would give the folder of 'user.username' instead of 'John'(one example of username)
I have also tried other ways like files/users/%user.username/%Y_%m_%d/
,but it would not give the folder with the user name. Not sure how the syntax should be or whether this is possible.
Can you give some suggestions on this? Thank you very much for your help and explanation.
Instead of a string try passing a function:
def generate_filename(self, filename):
url = "files/users/%s/%s" % (self.user.username, filename)
return url
class UserFiles(models.Model):
user = models.OneToOneField(User)
file = models.FileField(upload_to=generate_filename)
这篇关于Django模型与FileField - 动态'upload_to'参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!