Django动态文件上传路径

3

这是我的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/ 

然后我想上传文件到用户名目录中。请帮忙提供任何解决方案,谢谢。

1
具体是什么出了问题?你有收到任何异常吗? - Leistungsabfall
我在get_upload_file函数中没有得到用户名...我该怎么办? - NIKHIL RANE
1个回答

1

最终我找到了解决上述问题的方法。当我创建类实例时,将请求对象设置为该实例,并在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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接