Validate image size in django admin
use this function in your model file,
from django.core.exceptions import ValidationError
def validate_image(fieldfile_obj):
filesize = fieldfile_obj.file.size
megabyte_limit = 2.0
if filesize > megabyte_limit*1024*1024:
raise ValidationError("Max file size is %sMB" % str(megabyte_limit))
class Company(models.Model):
logo = models.ImageField("Logo", upload_to=upload_logo_to,validators=[validate_image], blank=True, null=True,help_text='Maximum file size allowed is 2Mb')
The right place to do this is during form validation.
A quick example (will edit/integrate with more info later):
from django.core.files.images import get_image_dimensions
from django.contrib import admin
from django import forms
class myForm(forms.ModelForm):
class Meta:
model = myModel
def clean_picture(self):
picture = self.cleaned_data.get("picture")
if not picture:
raise forms.ValidationError("No image!")
else:
w, h = get_image_dimensions(picture)
if w != 100:
raise forms.ValidationError("The image is %i pixel wide. It's supposed to be 100px" % w)
if h != 200:
raise forms.ValidationError("The image is %i pixel high. It's supposed to be 200px" % h)
return picture
class MyAdmin(admin.ModelAdmin):
form = myForm
admin.site.register(Example, MyAdmin)