不允许图像小于特定尺寸



我有一个保存用户个人资料图像的模型。如果上传的图像大于 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 像素时,不应上传该图片。但是,正在上传图像。我怎样才能阻止这种情况发生?

您可以在表单中执行此操作,而不是在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() 时,图像已经上传。所以最好以形式进行。