I have a problem with django ImageField. To be precise, with its download path and saving to database. I`ve set upload_to to the directory needed, and it saves files right where it should be.
photo = models.ImageField(
default="Person-595b40b65ba036ed117d315a.svg",
upload_to="static/img",
)
There should also be no problems with retrieving those photos as I added my directory to STATICFILES_DIRS:
STATIC_URL = "static/"
STATICFILES_DIRS = (
BASE_DIR / "static", "static/img",
)
But when it comes to the database, my photos are saved like this and when it comes to retrieving, django firstly goes to my static files directory, which is static/img and the searches for static/img/static/img/images.png which is not found for sure.
static/img/images.png
So my question is how to avoid path duplicating in database? How to make my images download to specified directory but appearing in the database without path so I could retrieve it without any changes in db?
Thanks in advance!!!
Check out Django's
MEDIA_URLandMEDIA_ROOTsettings here. In addition you can set theupload_toattribute to a function where you do some manipulation to path/filename, for instance:The custom function receives
instanceas the model instance that you are currently working with and afilename, which is pretty self-explanatory - the name of the uploaded file. With this code the file would be uploaded to yoursettings.MEDIA_ROOT/internal/file.pngpath