Django model with FileField — dynamic 'upload_to' argument

后端 未结 1 1983
花落未央
花落未央 2021-02-02 17:07

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 i

相关标签:
1条回答
  • 2021-02-02 17:43

    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)
    
    0 讨论(0)
提交回复
热议问题