问题
I have a model that saves user profile images. If the image that is uploaded is greater than 200x200 pixels, then we resize to 200x200. If the image is right at 200x200, then we return that image. What I want now is to throw an error to the user saying that this image is too small and is not allowed. Here's what I have:
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()
When an image is smaller than 200px in width or height, the image should not be uploaded. However, the image is being uploaded. How can I stop this from happening?
回答1:
Instead of doing that in save()
method, you can do it in forms:
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
Reason for this is because, when you have called save()
, image is already uploaded. So its better to do it in forms.
来源:https://stackoverflow.com/questions/54454515/not-allowing-images-small-than-certain-dimensions