Note that there are some explanatory texts on larger screens.

plurals
  1. PODjango custom validation in model form for imagefield (max file size etc.)
    primarykey
    data
    text
    <p>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.</p> <p>Here is the models.py:</p> <pre><code>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) </code></pre> <p>Here is the forms.py with the custom validation:</p> <pre><code>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 &gt; 1*1024*1024: raise ValidationError("Image file too large ( maximum 1mb )") if image._height &gt; 60 or image._width &gt; 468: raise ValidationError("Image dimensions too large ( maximum 468x60 pixels )") return image else: raise ValidationError("Couldn't read uploaded image") </code></pre> <p>From what I have read this should work but the image just uploads regardless of the size.</p> <p>Am I doing something wrong or is there a better way to go about doing this?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload