通过处理提交的 ImageFields 来更新保存时 Django 模型的属性
基本上,我试图保存一个包含 ImageField
的 Django 模型,并使用从 EXIF 数据中获取的值更新其 latitude
和 longitude
FloatFields包含在图像中(如果有)。
这是说明该问题的示例模型:
class GeoImage(models.Model):
image = models.ImageField(upload_to='/path/to/uploads')
latitude = models.FloatField(null=True, blank=True)
longitude = models.FloatField(null=True, blank=True)
def save(self):
# grab the path of the image of the ImageField
# parse the EXIF data, fetch latitude and longitude
self.latitude = fetched_latitude
self.longitude = fetched_longitude
return super(GeoImage, self).save()
您能发现问题吗?我不知道如何在模型实例实际保存之前访问图像文件路径,并且我无法保存记录,更新一些属性然后再次将其保存回来,因为它会创建一个 post_save 循环(理论上也是如此post_save
信号…
非常感谢
注意:我不需要 EXIF 数据提取或解析方面的帮助,只需在保存时更新整个模型的方法即可。 )
编辑:好的,您可以在保存记录之前访问文件对象并进一步处理它:
class GeoImage(models.Model):
image = models.ImageField(upload_to='/path/to/uploads')
latitude = models.FloatField(null=True, blank=True)
longitude = models.FloatField(null=True, blank=True)
def save(self):
latitude, longitude = gps_utils.process_exif(self.image.file)
if latitude: self.latitude = latitude
if longitude: self.longitude = longitude
return super(GeoImage, self).save(*args, **kwarg)
Basically I'm trying to save a Django model which contains an ImageField
, and updates its latitude
and longitude
FloatFields with values grabbed from the EXIF data contained in the image, if any.
Here's a sample model illustrating the issue:
class GeoImage(models.Model):
image = models.ImageField(upload_to='/path/to/uploads')
latitude = models.FloatField(null=True, blank=True)
longitude = models.FloatField(null=True, blank=True)
def save(self):
# grab the path of the image of the ImageField
# parse the EXIF data, fetch latitude and longitude
self.latitude = fetched_latitude
self.longitude = fetched_longitude
return super(GeoImage, self).save()
Can you spot the problem? I don't know how to access the image filepath before the model instance is actually saved, and I can't save the record, update some properties then save it back again, because it would create a post_save loop (and same goes theorically with a post_save
signal…
Any help much appreciated.
Note: I don't need help with EXIF data extraction nor parsing, just with the way to update the whole model on save().
Edit: Okay so you can access the file object and process it further before the record being saved:
class GeoImage(models.Model):
image = models.ImageField(upload_to='/path/to/uploads')
latitude = models.FloatField(null=True, blank=True)
longitude = models.FloatField(null=True, blank=True)
def save(self):
latitude, longitude = gps_utils.process_exif(self.image.file)
if latitude: self.latitude = latitude
if longitude: self.longitude = longitude
return super(GeoImage, self).save(*args, **kwarg)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
FileField 应返回一个类似文件的对象,您可以读取该对象来提取 exif 信息。
The FileField should return a file-like object that you can read to extract exif information.