4

Ive recently been experiementing with using django

I want to be able to run an uploaded file through imagemagick on the model save function, I realised this wasn't possible due to the file not being available till the instance had been saved

I've got it working were the save is called at the start which then allows access to the uploaded file then re saves once its populated the other fields

Is there a better way to achieve this? it just kinda feels wrong calling the save function twice

class uploadedFiles(models.Model):
orignal_image = models.FileField(upload_to='userimages/')
user = models.ForeignKey(User)
description = models.TextField(blank=True)


def __unicode__(self,force_insert=False, force_update=False):
    return "%s uploaded by %s" % (self.orignal_image.path, self.user) 

def save(self, force_insert=False, force_update=False):
    super(uploadedFiles, self).save()
    s = ''
    cmd = subprocess.Popen(['identify', '-verbose', self.orignal_image.path], stdout=subprocess.PIPE)
    for line in cmd.stdout:
        s += line
    self.description = s
    super(uploadedFiles, self).save()

2 Answers 2

0

It's better if you use the imaging library functions to collect image metadata. Then you just have to read the image data from the FileStorage instance of the image field. Just check for the documentation of file uploads. Also, when using Django's ImageField, it checks the uploaded file to see if is a valid image file, check the code for ImageField as a baseline to obtain more info about an image.

I would define an clean method to the model, this will get called just before calling the model's save method. In clean, then check the data stream of the image field with the PIL functions to obtain the metadata (or whatever library you want to use for this, as long as it accepts a data stream, not a physical file) and then fill the description field with the metadata.

Using the Django's Storage API is better, so you can extract metadata from files stored in the cloud (like Amazon S3), rather than just those stored in a local filesystem, making the code much more portable across deployments.

-1

Use Django's pre_save signal (docs, see also Signals in Django's documentation):

from django.db.models.signals import pre_save
from myapp.models import MyModel

def do_something(sender, **kwargs):
    pass
pre_save.connect(do_something, sender=MyModel)

Django will now call do_something before saving MyModel objects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.