I'm trying to generate dynamic file paths in django. I want to make a file system like this:
-- user_12
--- photo_1
--- photo_2
--- user_ 13
---- photo_1
I found a related question : Django Custom image upload field with dynamic path
Here, they say we can change the upload_to path and leads to https://docs.djangoproject.com/en/stable/topics/files/ doc. In the documentation, there is an example :
from django.db import models
from django.core.files.storage import FileSystemStorage
fs = FileSystemStorage(location='/media/photos')
class Car(models.Model):
...
photo = models.ImageField(storage=fs)
But, still this is not dynamic, I want to give Car id to the image name, and I cant assign the id before Car definition completed. So how can I create a path with car ID ??
You can use a callable in the upload_to
argument rather than using custom storage. See the docs, and note the warning there that the primary key may not yet be set when the function is called. This can happen because the upload may be handled before the object is saved to the database, so using ID
might not be possible. You might want to consider using another field on the model such as slug. E.g:
import os
def get_upload_path(instance, filename):
return os.path.join(
"user_%d" % instance.owner.id, "car_%s" % instance.slug, filename)
then:
photo = models.ImageField(upload_to=get_upload_path)