[Django]-Django accessing uploaded files in model custom save, best practice?

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.

Leave a comment