简体   繁体   English

Django model 通过图像调整大小保存两次

[英]Django model is saving twice with image resize

I am trying to resize images before upload using the following code.我正在尝试使用以下代码在上传之前调整图像大小。 However, I get two saved models after submitting the form when I apply the custom def save(self, *args, **kwargs): function.但是,当我应用自定义def save(self, *args, **kwargs): function 时,我在提交表单后得到了两个保存的模型。 Why is that?这是为什么?

class Players(models.Model):
    super().save(*args, **kwargs)

    author = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
    player_img = models.ImageField(upload_to='profile_pics', default="default.jpg", null=True, blank=True)

    def save(self, *args, **kwargs):

        img_read = storage.open(self.player_img.name, 'rb')
        img = Image.open(img_read)

        if img.height > 300 or img.width > 300:
            output_size = (300, 300)
            img.thumbnail(output_size)
            in_mem_file = io.BytesIO()
            img.convert('RGB').save(in_mem_file, format='JPEG')
            img.save(in_mem_file, format='JPEG')
            img_write = storage.open(self.player_img.name, 'w+')
            img_write.write(in_mem_file.getvalue())
            img_write.close()

        img_read.close()

Views.py视图.py

class player_add(LoginRequiredMixin, CreateView):
    model = Players
    template_name = 'player_create.html'

    form_class = forms.PlayerForm

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

super().save(*args, **kwargs) should be the last line of code in your def save(self, *args, **kwargs) method, not where it is now. super().save(*args, **kwargs)应该是def save(self, *args, **kwargs)方法中的最后一行代码,而不是现在的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM