How to avoid path duplication of images downloaded to database with django form

63 Views Asked by At

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!!!

1

There are 1 best solutions below

0
antpngl92 On

Check out Django's MEDIA_URL and MEDIA_ROOT settings here. In addition you can set the upload_to attribute to a function where you do some manipulation to path/filename, for instance:


class Foo(models.Model):
 def image_directory_path(instance, filename):
   return f'internal/{filename}_0{self.instance.pk}'

 image = models.ImageField(
        upload_to=image_directory_path,
        height_field=None,
        width_field=None,
        max_length=100,
    )

The custom function receives instance as the model instance that you are currently working with and a filename, which is pretty self-explanatory - the name of the uploaded file. With this code the file would be uploaded to your settings.MEDIA_ROOT/internal/file.png path