0

I want to clear the image from a profile model instance. I'm trying to accomplish this in the clean data function. The function works to resize the image but when I submit the form with 'clear' checkbox checked the picture is still there.

class ProfileEditForm(forms.ModelForm):
    image = forms.ImageField(required=False)
    bio = forms.CharField(required=False)

    class Meta:
        model = Profile
        fields = ('image', 'bio',)

    def clean_image(self, *args, **kwargs):

        from PIL import Image
        from io import BytesIO
        from django.core.files.uploadedfile import InMemoryUploadedFile
        from sys import getsizeof

        image = self.cleaned_data.get("image")
        if not image:
            image = None
            return image

        size = (135,135)
        im = Image.open(image)
        output = BytesIO()
        im.thumbnail(size)
        im.save(output, format='JPEG', quality=100)

        output.seek(0)
        image = InMemoryUploadedFile(output,'ImageField', "%s.jpg" %image.name.split('.')[0], 'image/jpeg', getsizeof(output), None)

        return image
Mint
  • 1,013
  • 1
  • 12
  • 29

1 Answers1

0

This did the trick

if not image:
    image = ''
    return image
Mint
  • 1,013
  • 1
  • 12
  • 29