django在更新保存时删除图像

时间:2018-01-04 00:54:18

标签: django django-models

我有以下清洁方法,如果图像太大,我会通过该方法缩小图像:

类CompanyForm(forms.ModelForm):    类Meta:         model =公司         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

我的缩小图片如下所示:

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

我第一次保存时,没有任何问题。当我第二次保存更新模型时,它会删除图像。

为什么会发生这种情况?

1 个答案:

答案 0 :(得分:1)

在更新视图的post方法中,将以下参数传递给表单

get_object它是我用来返回相关对象的自定义方法

如果您正在使用CBV

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

基于功能的视图

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