代码之家  ›  专栏  ›  技术社区  ›  Atma

django在更新保存时删除图像

  •  0
  • Atma  · 技术社区  · 8 年前

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

    类别CompanyForm(forms.ModelForm): 类元: 型号=公司 排除=(“有限”)

    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
    

    我的reduce图像如下所示:

    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 回复  |  直到 8 年前
        1
  •  1
  •   taoufik A    8 年前

    在更新视图的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():
              ....