Django验证ImageField的尺寸等 [英] Django validating ImageField dimensions etc

查看:208
本文介绍了Django验证ImageField的尺寸等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义的清洁方法如下:

I have a custom clean method below:

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小部件显示的复选框来清除它。当提交表单进行清除时,清除不会。

An image has been uploaded. I now want to clear it using the checkbox that appears using the ImageField widget. When submitting the form to make this clear take place the clear does not.

如果我删除我的自定义清洁方法,清除工作。因此,我想我的方法做错了。

If I remove my custom clean method the clear does work. Therefore I guess my method is doing something wrong.

推荐答案

当django意识到此验证时,有3个问题:

There are 3 problems when django realize this validations:


  1. Django需要获取这些字段的值,始终需要返回一个值

  2. 需要将类Meta与名称你使用的模型。

  3. 在这个句子中需要put .get这种方式

  1. Django need obtain the value of these field, always need return a value
  2. Need put class Meta with the name of the model you used.
  3. In this sentences need put .get this way

self.cleaned_data.get['image']


  • 代码如下所示:

  • The code looks like this:

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


  • 这篇关于Django验证ImageField的尺寸等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆