0

I want to create multiple copies of an image and resize them using celery after the original image was sent.

   def save_model(self, request, obj, form, change):
        updated = change
        super().save_model(request, obj, form, change)

        if not updated:
            logo = CompanyLogo(logo=form.cleaned_data['logo'], company=obj)
            logo.save()
            # Send Celery task to create resize images
            task_company_logo.delay(form.cleaned_data['logo'])

called by task method

def crop_image(path):
    image = Image.open(os.path.join(settings.MEDIA_ROOT, path))
    image.show()

I have the following error:

'InMemoryUploadedFile' is not JSON serializable

I understand the error, because I send the all image obj from the form, I just want to get the path to the original image.

user3541631
  • 3,686
  • 8
  • 48
  • 115

1 Answers1

1

form.cleaned_data['logo'] is returning an InMemoryFile which can not be passed directly to a celery task as an argument. You need to either save this file to a temporary location and pass the path to celery task or you can pass the name of the file from save_model method and celery task will use this name here:

task_company_logo.delay(filename) # pass filename here

image = Image.open(os.path.join(settings.MEDIA_ROOT, path))

to construct the path.

from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
path = default_storage.save('tmp/name.jpg', 
                         ContentFile(form.cleaned_data['logo'].read()))

EDIT: You can get the filename by using

if not updated:
    logo = CompanyLogo(logo=form.cleaned_data['logo'], company=obj)
    logo.save()
    # Send Celery task to create resize images
    filename = logo.logo.path # this can be passed to celery task
    task_company_logo.delay(filename)
Arpit Solanki
  • 9,567
  • 3
  • 41
  • 57
  • I save the original in save_model ( logo.save()), so I don't need a temporary file, but how I get the filename from save_model because save() doesn't return the object? – user3541631 Jan 08 '18 at 08:55