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

2024-05-05 00:04:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个modelform,它有一个名为“banner”的imagefield,我正在尝试验证文件大小和尺寸,如果图像太大,则提供一个错误。

下面是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")

从我所读到的应该可以工作,但图像只是上传不管大小。

我是做错了什么,还是有更好的办法?


Tags: imageselfipfalsetruedefaultserverport