在ImageField的模型形式Django的自定义验证(最大文件大小等)(Django custo

2019-07-31 04:30发布

我有了所谓的“旗帜”的ImageField的一个的ModelForm,我试图验证文件的大小和dimesions,如果图像是太大提供错误。

这里是models.py:

class Server(models.Model):
    id = models.AutoField("ID", primary_key=True, editable=False)
    servername = models.CharField("Server Name", max_length=20)
    ip = models.CharField("IP Address", max_length=50)
    port = models.CharField("Port", max_length=5, default='25565')
    banner = models.ImageField("Banner", upload_to='banners', max_length=100)
    description = models.TextField("Description", blank=True, max_length=3000)
    rank = models.IntegerField(default=0)
    votes = models.IntegerField(default=0)
    website = models.URLField("Website URL", max_length=200, blank=True)
    user = models.ForeignKey(User)
    motd = models.CharField("MOTD", max_length=150, default='n/a')
    playersonline = models.CharField("Online Players", max_length=7, default='n/a')
    online = models.BooleanField("Online", default=False)
    sponsored = models.BooleanField("Sponsored", default=False)
    lastquery = models.DateTimeField('Last Queried', auto_now=True)
    slugurl = models.SlugField("SlugURL", max_length=50)
    def __unicode__(self):
        return "%s (%s:%s)" % (self.servername, self.ip, self.port)

下面是与自定义验证forms.py:

class AddServer(ModelForm):
    class Meta:
        model = Server
        fields = ('servername', 'ip', 'port', 'website', 'description', 'banner')

     # Add some custom validation to our image field
    def clean_image(self):
        image = self.cleaned_data.get('banner', False)
        if image:
            if image._size > 1*1024*1024:
                raise ValidationError("Image file too large ( maximum 1mb )")
            if image._height > 60 or image._width > 468:
                raise ValidationError("Image dimensions too large ( maximum 468x60 pixels )")
            return image
        else:
            raise ValidationError("Couldn't read uploaded image")

从我读过这应该工作,但像刚刚上传无论大小。

我是不是做错了什么,或是否有更好的方式去这样做呢?

Answer 1:

只是回答这里备案:

海报没有检查form.cleaned_data(),这意味着clean_xxx验证没有得到运行。



Answer 2:

方法的名称应clean_<field name>在这种情况下clean_banner

对于未来的参考,我会的地方,我在最近的一个项目(名称必须适应与OP代码工作)使用的代码片段:

from PIL import Image
from django.utils.translation import ugettext as _

def clean_photo(self):
    image = self.cleaned_data.get('photo', False)

    if image:
        img = Image.open(image)
        w, h = img.size

        #validate dimensions
        max_width = max_height = 500
        if w > max_width or h > max_height:
            raise forms.ValidationError(
                _('Please use an image that is smaller or equal to '
                  '%s x %s pixels.' % (max_width, max_height)))

        #validate content type
        main, sub = image.content_type.split('/')
        if not (main == 'image' and sub.lower() in ['jpeg', 'pjpeg', 'png', 'jpg']):
            raise forms.ValidationError(_('Please use a JPEG or PNG image.'))

        #validate file size
        if len(image) > (1 * 1024 * 1024):
            raise forms.ValidationError(_('Image file too large ( maximum 1mb )'))
    else:
        raise forms.ValidationError(_("Couldn't read uploaded image"))
    return image


文章来源: Django custom validation in model form for imagefield (max file size etc.)