【问题标题】:Django custom validation in model form for imagefield (max file size etc.)图像字段模型形式的 Django 自定义验证(最大文件大小等)
【发布时间】:2012-08-21 05:09:21
【问题描述】:

我有一个模型表单,它有一个名为“横幅”的图像字段,我正在尝试验证文件大小和尺寸,如果图像太大,则会提供错误。

这里是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")

根据我的阅读,这应该可以,但是无论大小如何,图片都会上传。

我做错了什么还是有更好的方法来做这件事?

【问题讨论】:

  • 看起来你的加薪没有被执行。检查 if 条件是否真的为真。 (在你的views.py中你实际上是在检查cleaned_data)
  • 谢谢!原来我忘了检查cleaned_data! 掌心
  • image._height 和 image._width 似乎不存在?我发现: from django.core.files.images import get_image_dimensions 这似乎对我更有效。

标签: python django validation modelform imagefield


【解决方案1】:

这里只是为了记录而回答:

发帖人没有检查form.cleaned_data(),这意味着clean_xxx 验证没有运行。

【讨论】:

  • 是的,不知道我是怎么错过的。感谢您的帮助。
【解决方案2】:

方法的名称应为clean_<field name>,在本例中为clean_banner

为了将来参考,我将放置我在最近的一个项目中使用的代码的 sn-p(名称必须适合与 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-01
    • 2013-10-06
    • 1970-01-01
    • 2019-09-06
    • 2017-01-06
    相关资源
    最近更新 更多