更新对象时重新上传图像

image being re-uploaded when updating object

在我的博客 post 模型中,我重写了保存方法以调用一个函数来压缩正在上传的图像。这按预期工作。但是,当我使用更新视图并对 post 进行更改时,图像会重新上传到 s3 存储桶并替换模型上的原始图像。

如果我从压缩功能中删除所有代码并只拥有它 return 图片,当使用更新视图时它不会重新上传图片。

如何防止图片在updateview时被重新上传

型号:

    def compress(image):
    
    img = Image.open(image)
    img = img.convert("RGB")

    (w, h) = img.size   # current size (width, height)
    if w > 2000:
        new_size = (w//2, h//2)  # new size
        img = img.resize(new_size, Image.ANTIALIAS)
        (w, h) = img.size
        if w > 2000:
            new_size = (w//2, h//2)  # new size
            img = img.resize(new_size, Image.ANTIALIAS)

    im_io = BytesIO() 
    img.save(im_io, 'JPEG', quality=70, optimize=True) 

    new_image = File(im_io, name=image.name)

    return new_image


class Post(models.Model):
    image = models.ImageField(storage=PublicMediaStorage(), upload_to=path_and_rename, validators=[validate_image])
    ....


    def save(self, *args, **kwargs): 
        self.slug = slugify(self.title)

        if self.image:
            # call the compress function
            new_image = compress(self.image)
            # set self.image to new_image
            self.image = new_image

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

查看:

class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
    model = Post
    form_class = PostFormUpdate
    template_name = 'blog/update_post.html'
   
    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

    def test_func(self):
        post = self.get_object()
        if self.request.user.id == post.author_id:
            return True
        return False

self._state.adding 可用于检查它是否是初始 save() 调用。

def save(self, *args, **kwargs): 
    self.slug = slugify(self.title)
    initial = self._state.adding

    if self.image and initial:
        # call the compress function
        new_image = compress(self.image)
        # set self.image to new_image
        self.image = new_image

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