【问题标题】:Not allowing images small than certain dimensions不允许小于特定尺寸的图像
【发布时间】:2019-01-31 06:22:04
【问题描述】:

我有一个保存用户个人资料图像的模型。如果上传的图像大于 200x200 像素,则我们将大小调整为 200x200。如果图像是正确的 200x200,那么我们返回该图像。我现在想要的是向用户抛出一个错误,说这个图像太小并且不允许。这是我所拥有的:

class Profile(models.Model):
    GENDER_CHOICES = (
        ('M', 'Male'),
        ('F', 'Female'),
    )
    user    = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
    bio     = models.CharField(max_length=200, null=True)
    avatar  = models.ImageField(upload_to="img/path")
    gender  = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True)

    def save(self, *args, **kwargs):
        super(Profile, self).save(*args, **kwargs)
        if self.avatar:
            image = Image.open(self.avatar)
            height, width = image.size
            if height == 200 and width == 200:
                image.close()
                return

            if height < 200 or width < 200:
                return ValidationError("Image size must be greater than 200")
            image = image.resize((200, 200), Image.ANTIALIAS)
            image.save(self.avatar.path)
            image.close()

当图像的宽度或高度小于 200 像素时,不应上传该图像。但是,图像正在上传。我怎样才能阻止这种情况发生?

【问题讨论】:

    标签: django django-models django-views


    【解决方案1】:

    您可以在表单中这样做,而不是在 save() 方法中这样做:

    from django.core.files.images import get_image_dimensions
    from django import forms
    
    class ProfileForm(forms.ModelForm):
       class Meta:
           model = Profile
    
       def clean_avatar(self):
           picture = self.cleaned_data.get("avatar")
           if not picture:
               raise forms.ValidationError("No image!")
           else:
               w, h = get_image_dimensions(picture)
               if w < 200:
                   raise forms.ValidationError("The image is %i pixel wide. It's supposed to be more than 200px" % w)
               if h < 200:
                   raise forms.ValidationError("The image is %i pixel high. It's supposed to be 200px" % h)
           return picture
    

    这是因为,当您拨打save() 时,图片已经上传。所以最好用表格来做。

    【讨论】:

    • 表格或清洁。保存有点晚了
    • 嗯,我正在尝试在我的模板中执行 {{ form.avatar.errors|striptags }},但我没有看到错误消息。此外,这有效,图像不再上传。
    • 嗯,你可以不试试striptags吗?即{{ form.avatar.errors }}
    猜你喜欢
    • 1970-01-01
    • 2020-10-08
    • 1970-01-01
    • 2015-01-27
    • 1970-01-01
    • 2017-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多