Allow name of file in FileField/ImageField to be based on primary key
|Reported by:||krzyk||Owned by:||nobody|
|Has patch:||no||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
Currently there is no way to prevent admin from uploading file with the same name (which will result in overwriting the previous file) (having zillions of date based directiories is not a good idea).
The simplest solution would be to use primary key as the file name, but when upload_to callable is called the instance doesn't have the primary key yet.
class Gallery(models.Model): name = models.CharField(max_length=255) def image_upload(instance, filename): return 'content/gallery/' + gallery.id + '/' + instance.id + '.jpg' # extension can be retrieved from filename class Image(models.Model): gallery = models.ForeignKey(Gallery) title = models.CharField(max_length=255) image = models.ImageField(upload_to=image_upload)
The above results in creation of None.jpg file.