Django表格对某些宽度和高度的图像场验证

问题描述 投票:0回答:1

我正在尝试验证表单级别的图像维度,并在提交的照片不符合图像尺寸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',
django height width imagefield
1个回答
0
投票

你可以用两种方式做到这一点

  1. 在模型中验证 来自django.core.exceptions导入ValidationError 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])
  2. 清洁形式 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")
© www.soinside.com 2019 - 2024. All rights reserved.