0

I have 1 image per model object instance and I think a reliable way to name each one would be to use the ID of the object. How can I set the ImageField of my model to use the ID of the object?

User
  • 23,729
  • 38
  • 124
  • 207

1 Answers1

0

An ImageField's upload_to parameter is what is used by Django to determine uploaded files' path. It can be passed a callable, called with the model instance and original filename as parameters. That allows custom and instance specific behaviours.

However, using the ID in the filename is not a good idea because, as stated in the documentation, when upload_to is called, the model instance has, in most cases, not yet been saved to the database. It means that on object creation, the object does not have an ID yet.

A solution could be to always same model instances first and only then set their ImageField but does two saves to the database and requires extra work from you. I advise you to find another unique way to name your images. Have a look at that question for example.

Community
  • 1
  • 1
aumo
  • 5,344
  • 22
  • 25