Django自定义验证以模型形式用于imagefield(最大文件大小等) [英] Django custom validation in model form for imagefield (max file size etc.)

查看:407
本文介绍了Django自定义验证以模型形式用于imagefield(最大文件大小等)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型窗体,其中有一个名为"banner"的图像字段,我正在尝试验证文件大小和尺寸,并在图像太大时提供一个错误.

I have a modelform that has an imagefield called 'banner' and I am trying to validate the file size and dimesions and provide an error if the image is too large.

这是models.py:

Here is the 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:

Here is the forms.py with the custom validation:

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

从我阅读的内容来看,这应该可以工作,但是无论大小如何,图像都只会上传.

From what I have read this should work but the image just uploads regardless of the size.

我做错了什么吗?还是有更好的方法来做到这一点?

Am I doing something wrong or is there a better way to go about doing this?

推荐答案

只需在此处回答即可:

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

The poster didn't check the form.cleaned_data(), which means that clean_xxx validation didn't get run.

这篇关于Django自定义验证以模型形式用于imagefield(最大文件大小等)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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