Django验证ImageField维度等

前端之家收集整理的这篇文章主要介绍了Django验证ImageField维度等前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个自定义清洁方法如下:
def clean_image(self):
    image = self.cleaned_data['image']
    if image:
        from django.core.files.images import get_image_dimensions
        w,h = get_image_dimensions(image)
        if not image.content_type in settings.VALID_IMAGE_FORMATS:
            raise forms.ValidationError(u'Only *.gif,*.jpg and *.png images are allowed.')
        if w > settings.VALID_IMAGE_WIDTH or h > settings.VALID_IMAGE_HEIGHT:
            raise forms.ValidationError(u'That image is too big. The image needs to be ' + str(settings.VALID_IMAGE_WIDTH) + 'px * ' + str(settings.VALID_IMAGE_HEIGHT) + 'px (or less).')
        return image

问题场景是这样的:

上传图片.我现在想要使用ImageField小部件显示的复选框清除它.提交表格时,明确表示不清楚.

如果我删除自定义清理方法,则清除确实有效.因此我猜我的方法做错了.

解决方法

当django实现这个验证时有3个问题:

> Django需要获取这些字段的值,总是需要返回一个值
>需要将类Meta与您使用的模型的名称放在一起.
>在这句话中需要把这种方式放进去

self.cleaned_data.get['image']

>代码如下所示:

class Meta: 
    model = NameModel    

def clean_image(self):
    image = self.cleaned_data.get['image']
    if image:
        from django.core.files.images import get_image_dimensions
        w,*.jpg and *.png images are allowed.')
        if w > settings.VALID_IMAGE_WIDTH or h > settings.VALID_IMAGE_HEIGHT:
            raise forms.ValidationError(u'That image is too big. The image needs to be ' +     str(settings.VALID_IMAGE_WIDTH) + 'px * ' + str(settings.VALID_IMAGE_HEIGHT) + 'px (or less).')
    return image

猜你在找的Python相关文章