2

I am trying to convert a Pillow image to Django ImageField.

Basically, I:

  • Take an ImageField as input (from a user submitted form)
  • Open it with Pillow
  • Process it (blur it in that case)
  • Pass it back to my Django Form
  • Try to save the Form ⚠️

This is at the last step that I have the error 'Image' object has no attribute '_committed' (which I believe is that Django is unable to save a Pillow image and that it needs to be converted)


def upload_media(request):
    if request.method == 'POST':
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            image = form.cleaned_data['image']

            pil_image = Image.open(image)
            blurred_image = pil_image.filter(ImageFilter.GaussianBlur(100))

            post = Post(image=image, blurred_image=blurred_image)
            post.save()

    return redirect('index')

mincom
  • 670
  • 5
  • 21

1 Answers1

3

in django file data from request converted into fileupload object . you need to get this image and conver it to byte and the conver it into fileupload object with InMemoryUploadedFile class . output of this class is fileupload object .

image = Img.open(field)
image = image.convert('RGB')
image = image.resize((800, 800), Img.ANTIALIAS)
output = io.BytesIO()
image.save(output, format='JPEG', quality=85)
output.seek(0)
new_pic= InMemoryUploadedFile(output, 'ImageField',
                                    field.name,
                                    'image/jpeg',
                                    sys.getsizeof(output), None)
biswa1991
  • 530
  • 3
  • 8