Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
django在更新保存时删除图像_Django_Django Models - Fatal编程技术网

django在更新保存时删除图像

django在更新保存时删除图像,django,django-models,Django,Django Models,如果图像太大,我可以使用以下方法缩小图像: 类别CompanyForm(forms.ModelForm): 类元: 模型=公司 排除=('limited') 我的reduce图像如下所示: def reduce_image(image_field, height_max): if image_field: try: image_file2 = BytesIO(image_field.read()) image = Ima

如果图像太大,我可以使用以下方法缩小图像:

类别CompanyForm(forms.ModelForm): 类元: 模型=公司 排除=('limited')

我的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
我第一次保存时,就没有问题了。当我保存第二次更新模型时,它会删除图像


为什么会发生这种情况?

在更新视图的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():
          ....
if request.method == 'POST':
    form = CompanyForm(request.POST, request.FILES, instance=get_object())
    if form.is_valid():
          ....