特定宽度和高度的 Django Form Imagefield 验证

标签 django height width imagefield

我正在尝试验证表单级别的图像尺寸,如果提交的照片不符合图像尺寸 1080x1920 的要求,则会向用户显示一条消息。我不想将宽度和高度大小存储在数据库中。我尝试使用 Imagefield 宽度和高度属性。但它不起作用。

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',

最佳答案

有两种方式

  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")
    

关于特定宽度和高度的 Django Form Imagefield 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54976444/

相关文章:

python - django 如何从互联网下载文件

python - 使用 django-social-auth 出现导入错误

jquery - 如何根据内容的变化动态设置两行的高度

jquery - 如何按高度和宽度对 html 元素进行排序?

width - 显示 : Inline block - What is that space?

javascript - 从 Javascript 为 Canvas 设置属性失败

django - Django LoginView 的success_url?

python - 在 Django 中按月分组并检索为 datetime.date()

html - 保持div中的信息始终以特定行数显示

ios - 为什么Scrollview和子view大小有时不一致