I'm trying to create a simple photo gallery with the default Django admin. I'd like to save a sample photo for each gallery, but I don't want to keep the filname. Instead of the filename, I'd like to save the id of the model (N.jpg
). But the first time I want to save the object the id does not exist. How could I know the next auto increment in the model, or somehow save the model data before the upload with super.save
and after upload the file when self.id
is exists? Is there a cool solution?
Something like this:
def upload_path_handler(instance, filename):
ext = filename extension
return "site_media/images/gallery/{id}.{ext}".format(id=instance.nextincrement, ext=ext)
class Gallery(models.Model):
name = models.TextField()
image = models.FileField(upload_to=upload_path_handler)
And maybe store the filename in a different field.
Using Louis's answer, here is recipe to process all
FileField
in the model:In django 1.7, the proposed solutions didn't seem to work for me, so I wrote my FileField subclasses along with a storage subclass which removes the old files.
Storage:
FileField:
and my upload_to callables look like this:
I ran into the same problem. Okm's answer sent me on the right path but it seems to me it is possible to get the same functionality by just overriding the
save()
method.This definitely saves the information correctly.
The image file gets saved before Gallery instance. So you have to split the saving to two phases by using signals w/ Gallery instance itself carrying the state:
The upload_path_handler looks like
I suggest using ImageField instead of FileField for type-checking if the field is for image uploading only. Also, you may want to normalize filename extension (which is unnecessary because of the mimetype) like