Skip to main content
 首页 » 编程设计

python之Django动态文件上传路径

2025年05月04日32sharpest

这是我的 Django 代码。

我想将我的文件上传到特定位置,该路径是动态创建的。

def get_upload_file(instance, filename): 
   today_date = datetime.datetime.today().date() 
   directory = 'Data/'+ str(today_date) 
   if not os.path.exists(directory): 
       os.makedirs(directory) 
   full_path = str(directory)+"/%s" %(filename) 
   print "full_path --> ",full_path 
   # user = updated_path() 
   # print user 
   return full_path 
 
 
class UploadFile(models.Model): 
   path = models.FileField(upload_to=get_upload_file) 

我正在尝试用上面的代码上传文件,但我想上传到其中的另一个目录,它的名字在用户名上。

预期输出

Data/2015-08-16/username/  

然后我想上传用户名目录下的文件

任何解决方案请帮助我

请您参考如下方法:

最后我得到了上述问题的解决方案。当我创建类实例时,将请求对象设置为该实例并在 get_upload_file 函数中访问该请求对象

 class UploadFile(models.Model): 
       path = models.FileField(upload_to=get_upload_file) 
       reqObj = None 
 
       def set_reqObj(self, request): 
           self.reqObj = request 
 
new_file = UploadFile(path = afile) 
new_file.set_reqObj(request) 

在 get_upload_file 函数中使用 reqObj

instance.reqObj.user.username 

更新的 get_upload_file 函数是

def get_upload_file(instance, filename): 
   today_date = datetime.datetime.today().date() 
   directory = 'Data/'+ str(today_date)+'/'+instance.reqObj.user.username 
   if not os.path.exists(directory): 
       os.makedirs(directory) 
   full_path = str(directory)+"/%s" %(filename) 
   return full_path