Django model with FileField — dynamic 'upload_to' argument

▼魔方 西西 提交于 2019-12-31 10:42:18

问题


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.


回答1:


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)


来源:https://stackoverflow.com/questions/17539720/django-model-with-filefield-dynamic-upload-to-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!