I have a model where my goal is to generate the primary key (a character string) and then rename the uploaded file to match that string. This is my shortened model and the upload_to function I use.
class Thing(models.Model):
id = models.CharField(primary_key=True, max_length=16)
photo = ImageField('Photo', upload_to=upload_path, null=False, blank=False)
...
def upload_path(instance, filename):
if not instance.id:
randid = random_id(16) # This returns a 16 character string of ASCII characters
while Thing.objects.filter(id=randid).exists():
logger.error("[Thing] ThingID of %s already exists" % randid)
randid = random_id(16)
instance.id = randid
return "%s%s" % ("fullpath/",randid)
This results in the image being properly renamed to a random string in the appropriate path. The primary key, however, is set to an empty string.
How can I use a generated primary key to rename an ImageField file and properly save the primary key that is generated?
I ended up removing the
upload_tocall back and doing this all inThing‘ssave()method.