How to assign filename to Image in Django based on EXIF DateTime
How to assign filename to Image in Django based on EXIF DateTime
I would like to read EXIF information from a user-uploaded image in Django, then use that EXIF info to generate the filename to store the image as (under the animal_img/alfred-0012
directory), for example:
animal_img/alfred-0012
Original filename: P1110438.JPG
P1110438.JPG
Date taken: 2012-07-22
2012-07-22
Name: Alfred
Alfred
Intended filename: alfred-20120722.jpg
alfred-20120722.jpg
Somehow, this had been working up until recently, but Django has been complaining about not finding the file with [Errno 2] No such file or directory: 'P1110438.JPG'
[Errno 2] No such file or directory: 'P1110438.JPG'
The code I've been using in my model to rename the images:
def img_namer(instance, filename):
path = 'animal_img/%s-%04d/' % (instance.name.lower(), instance.id)
name = instance.name.lower() + Image.open(filename)._getexif()[36867] + ".jpg"
return os.path.join(path, name)
image = models.ImageField(
default=None,
blank=True,
upload_to=img_namer,
)
I can see the limitations with trying to open the ImageFile before it's been properly saved, however this had been working, like I said, so maybe I'm doing something wrong? Any help is appreciated!
1 Answer
1
I found your question while trying to solve a similar problem...
By replacing Image.open(filename)
with Image.open(instance.image)
it works for me.
Image.open(filename)
Image.open(instance.image)
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.