开发者

Updating properties of a Django model on save with processing of submitted ImageFields

开发者 https://www.devze.com 2023-01-31 11:00 出处:网络
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.

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 =开发者_Go百科 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)


The FileField should return a file-like object that you can read to extract exif information.

0

精彩评论

暂无评论...
验证码 换一张
取 消