2

I want to allow users upload an image through the Django admin, crop and scale that image in memory (probably using PIL), and save it to Amazon S3 without saving the image on the local filesystem. I'll save the image path in my database, but that is the only aspect of the image that is saved locally. I'd like to integrate this special image upload widget into the normal model form on the admin edit page.

This question is similar, except the solution is not using the admin interface.

Is there a way that I can intercept the save action, do manipulations and saving of the image to S3, and then save the image path and the rest of the model data like normal? I have a pretty good idea of how I would crop and scale and save the image to S3 if I can just get access to the image data.

Community
  • 1
  • 1
davidscolgan
  • 7,508
  • 9
  • 59
  • 78

2 Answers2

4

See https://docs.djangoproject.com/en/dev/topics/http/file-uploads/#changing-upload-handler-behavior

If images are smaller than a particular size, the will already be stored only in memory, so you can likely tune the FILE_UPLOAD_MAX_MEMORY_SIZE parameter to suit your needs. Additionally, you'll have to make sure that you don't access the .path field of these uploaded images, because that will cause them to be written out to a file. Instead, use (for example) the .read() method. I haven't tested this, but I believe this will work:

image = PIL.Image(request.FILES['my_file'])
David Wolever
  • 148,955
  • 89
  • 346
  • 502
  • This is very helpful to know, but where would I put this line if I was using the Django admin? – davidscolgan Dec 28 '11 at 18:59
  • You wouldn't. The simplest way to do it would be to create a new model field called, say, `ThumbnailingImageField` (probably a subclass of `ImageField`), which would create a thumbnail of the image and save that along with the full-sized image. – David Wolever Dec 28 '11 at 21:47
  • Also, vis a vi storing on S3: http://stackoverflow.com/questions/5044982/django-storage-backend-for-s3 – David Wolever Dec 28 '11 at 21:47
0

Well if you don't want to touch the Admin part of Django then you can define scaling in the models save() method. But when using the ImageField in Django. Django can actually do the saving for you. It has height and width options available.

https://docs.djangoproject.com/en/dev/ref/models/fields/#imagefield

For uploading to S3 I really suggest using django-storages backends from:

https://bitbucket.org/david/django-storages/src (preferably S3-boto version)

That way you basically will not have to write any code yourself. You can just use available libraries and solutions that people have tested.

madisvain
  • 259
  • 1
  • 2