Dynamic File Path in Django -
i'm trying generate dynamic file paths in django. want make file system this:
-- user_12 --- photo_1 --- photo_2 --- user_ 13 ---- photo_1
i found related question : django custom image upload field dynamic path
here, can change upload_to path , leads https://docs.djangoproject.com/en/stable/topics/files/ doc. in documentation, there example :
from django.db import models django.core.files.storage import filesystemstorage fs = filesystemstorage(location='/media/photos') class car(models.model): ... photo = models.imagefield(storage=fs)
but, still not dynamic, want give car id image name, , cant assign id before car definition completed. how can create path car id ??
you can use callable in upload_to
argument rather using custom storage. see docs, , note warning there primary key may not yet set when function called (because upload may handled before object saved database), using id
might not possible. might wan consider using field on model such 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)
Comments
Post a Comment