我想创建一个图像的多个副本,并在发送原始图像后使用芹菜调整它们的大小。
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'])
通过任务方法调用
def crop_image(path):
image = Image.open(os.path.join(settings.MEDIA_ROOT, path))
image.show()
我有以下错误:
'InMemoryUploadedFile' is not JSON serializable
我理解错误,因为我从表单发送了所有图像obj,我只是想获得原始图像的路径。
答案 0 :(得分:1)
form.cleaned_data['logo']
返回一个InMemoryFile
,它不能作为参数直接传递给芹菜任务。您需要将此文件保存到临时位置并将路径传递给celery任务,或者您可以从save_model
方法传递文件的名称,芹菜任务将在此处使用此名称:
task_company_logo.delay(filename) # pass filename here
image = Image.open(os.path.join(settings.MEDIA_ROOT, 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()))
编辑: 您可以使用
获取文件名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)