Django:UpdateView,创建另一个以前的图像

Django: UpdateView, creating another previous image

如果我更改模板中的某些内容但不更改图像字段并发送它,django 会使用另一个名称创建相同的图像。 f.e previous_imagename_{random_generated_letters}.jpg... Django 使用以前的图像名称并通过向以前的图像添加一些生成的短代码来创建相同的图像文件。

如果在模型中删除 def save() 它可以工作(而不是创建另一个模型)但我需要在保存到数据库之前更改图像大小。

views.py

class Edit(UpdateView):
    model = User_data
    form_class = EditProfileFormExtra
    template_name = 'account/edit.html'
    slug_field = "slug"

    def get_success_url(self):
        return reverse('accounts:edit', kwargs={'slug': self.kwargs['slug']})

models.py

class User_data(models.Model):
    username = models.OneToOneField(User, on_delete = models.CASCADE)
    image = models.ImageField(upload_to = get_upload_path, default='default/profile_photo_default.jpg')
    def save(self,*args, **kwargs):
        if self.image:
            #Opening the uploaded image
            im = Image.open(self.image)

            if im.mode in ("RGBA", "P"): 
                im = im.convert("RGB")

            output = BytesIO()
            w, h = im.size

            #Resize/modify the image
            if w > 1000 or h > 1000:
                d = w//1000 if w >= h else h//1000
            else:
                d = 1

            #Resizing
            im = im.resize((w//d, h//d))

            #after modifications, save it to the output
            im.save(output, format='JPEG', quality=100)
            output.seek(0)

            #change the imagefield value to be the newley modifed image value
            self.image = InMemoryUploadedFile(output,'ImageField', "%s.jpg" %self.image.name.split('.')[0], 'image/jpeg', sys.getsizeof(output), None)

        super(User_data,self).save(*args, **kwargs)

我遇到了同样的问题,我找到的解决方法是使用 django-cleanup

The django-cleanup app automatically deletes files for FileField, ImageField and subclasses. When a FileField’s value is changed and the model is saved, the old file is deleted. When a model that has a FileField is deleted, the file is also deleted. A file that is set as the FileField’s default value will not be deleted.