Atma
Atma

Reputation: 29767

django removes image on update save

I have the following clean method by which I reduce an image if it is too large:

class CompanyForm(forms.ModelForm): class Meta: model = Company exclude = ('limited')

def clean_image(self):
    image_field = self.cleaned_data.get('image')

    if image_field:
        reduced_image = reduce_image(image_field, 550)
        return reduced_image
    else:
        raise forms.ValidationError('You must upload a square logo image')

    return image_field

My reduce image looks like the following:

def reduce_image(image_field, height_max):

    if image_field:

        try:
            image_file2 = BytesIO(image_field.read())
            image = Image.open(image_file2).convert('RGB')
            print(image)
        except:
            #raise ValidationError('There was a problem with the image, please try another.')
            print('returning from image errror')
            return image_field

        w, h = image.size
        print('image width:'+str(w))
        print('image height:'+str(h))

        if h > height_max:
            print('height toolarge')
            ratio = h/float(w)
            new_height = ratio * height_max

            image = image.resize((int(height_max), int(new_height)), Image.ANTIALIAS)
            image_file = BytesIO()
            image.save(image_file, 'JPEG', quality=90)
            image_field.file = image_file
            print(image_file)


    return image_field

The first time I save, it saves no problem. When I save a second time to update the model, it removes the image.

Why might this be happening?

Upvotes: 0

Views: 33

Answers (1)

taoufik A
taoufik A

Reputation: 1410

In the post method of your update view pass the following arguments to your form

get_object it's a custom method that I use to return the concerned object

If you're using CBV

def post(self, request, *args, **kwargs):
    self.form_class(request.POST, request.FILES, instance=self.get_object())
    ....

For function based views

if request.method == 'POST':
    form = CompanyForm(request.POST, request.FILES, instance=get_object())
    if form.is_valid():
          ....

Upvotes: 1

Related Questions