【问题标题】:Updating properties of a Django model on save with processing of submitted ImageFields通过处理提交的 ImageFields 在保存时更新 Django 模型的属性
【发布时间】:2010-12-18 22:40:45
【问题描述】:

基本上,我正在尝试保存一个包含ImageField 的 Django 模型,并使用从图像中包含的 EXIF 数据中获取的值(如果有)更新其 latitudelongitude 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 数据提取或解析方面的帮助,只需要在 save() 上更新整个模型的方法即可。

编辑:好的,这样您就可以在保存记录之前访问文件对象并进一步处理它:

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)

【问题讨论】:

    标签: django django-models signals django-orm imagefield


    【解决方案1】:

    FileField 应该返回一个类似文件的对象,您可以读取该对象以提取 exif 信息。

    【讨论】:

    • 确实!为了记录,我编辑了问题以反映可能的实现。
    猜你喜欢
    • 2018-03-13
    • 1970-01-01
    • 2017-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多