You need to have a FileField
with the upload_to
that calls to a callback, see [1]
Your callback should call a wrapper method which gets an instance as one of the params and filename as the other. [2]
Change it the way you like and return the new path [3]
1. LOGIC
FileField(..., upload_to=method_call(params),....)
2. define method
def method_call(params):
return u'abc'
3. Wrapper:
def wrapper(instance, filename):
return method
this is the rapper method that you need for getting the instance.
def wrapper(instance, filename):
... Your logic
...
return wrapper
Complete Code
def path_and_rename(path, prefix):
def wrapper(instance, filename):
ext = filename.split('.')[-1]
project = "pid_%s" % (instance.project.id,)
# get filename
if instance.pk:
complaint_id = "cid_%s" % (instance.pk,)
filename = '{}.{}.{}.{}'.format(prefix, project, complaint_id, ext)
else:
# set filename as random string
random_id = "rid_%s" % (uuid4().hex,)
filename = '{}.{}.{}.{}'.format(prefix, project, random_id, ext)
# return the whole path to the file
return os.path.join(path, filename)
return wrapper
Call to Method
sales_attach = models.FileField("Attachment", upload_to=path_and_rename("complaint_files", 'sales'), max_length=500,
help_text="Browse a file")
Hope this helps.
Thanks.