I want the filenames to be random and therefore I use upload_to function which returns a random filename like so:
from uuid import uuid4
import os
def get_random_filename(instance, filename):
ext = filename.split('.')[-1]
filename = "%s.%s" % (str(uuid4()), ext)
return os.path.join('some/path/', filename)
# inside the model
class FooModel(models.Model):
file = models.FileField(upload_to=get_random_filename)
However I would like to save the original filename to an attribute inside the model. Something like this does not work:
def get_random_filename(instance, filename):
instance.filename = filename
ext = filename.split('.')[-1]
filename = "%s.%s" % (str(uuid4()), ext)
return os.path.join('some/path/', filename)
# inside the model
class FooModel(models.Model):
file = models.FileField(upload_to=get_random_filename)
filename = models.CharField(max_length=128)
How can I do it?
Thank you.
The posted code normally works, perhaps the actual code is
Note the switching of the ordering of the fields above.
This won’t work because: the
upload_to()is invoked by thepre_save(), here in the code, when the actual value of theFileFieldis required. You could find that the assignment to the attributefilenamein theupload()is after the generating of the first paramfilenamein the inserting sql. Thus, the assignment does not take effect in the generated SQL and only affects the instance itself.If that’s not the issue, please post the code you typed in shell.