Here its my django code.
I want to upload my file on specific location and that path is created dynamically.
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)
I am trying above code to upload file but i want to another directory in it and its name is on username.
expected output
Data/2015-08-16/username/
then i want to upload file in username directory
any solution please help me
Finally I got a solution for the above problem. When I am creating class instance set request object to that instance and access that request object in get_upload_file function
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)
use reqObj in get_upload_file function
instance.reqObj.user.username
updated get_upload_file function is
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With