我正在尝试验证表单级别的图像维度,并在提交的照片不符合图像尺寸1080x1920的要求时向用户显示消息。我不想在数据库中存储宽度和高度大小。我尝试使用Imagefield的width和height属性。但它没有用。
class Adv(models.Model):
image = models.ImageField(upload_to=r'photos/%Y/%m/',
width_field = ?,
height_field = ?,
help_text='Image size: Width=1080 pixel. Height=1920 pixel',
你可以用两种方式做到这一点
def validate_image(image):
max_height = 1920
max_width = 1080
height = image.file.height
width = image.file.width
if width > max_width or height > max_height:
raise ValidationError("Height or Width is larger than what is allowed")
class Photo(models.Model):
image = models.ImageField('Image', upload_to=image_upload_path, validators=[validate_image])
def clean_image(self):
image = self.cleaned_data.get('image', False)
if image:
if image._height > 1920 or image._width > 1080:
raise ValidationError("Height or Width is larger than what is allowed")
return image
else:
raise ValidationError("No image found")