Need to use an ImageField in Django with a limit on filesize while still allowing empty entries?

Here’s a class that subclasses the ImageField and allows you to set a limit on filesize while still allowing empty entries.


class ImageField50KB(forms.ImageField):
    def __init__(self, *args, **kwargs):
        super(ImageField50KB, self).__init__(*args, **kwargs)

        self.label = (u'Passport (Max 50kB)')

        self.helptext = (u'Attach a current passport photograph')

    def clean(self, data, initial):
        if not data and initial:
            return initial
        f = super(ImageField50KB, self).clean(data)

        if not (f.size <= 50000):
             raise forms.ValidationError((u'Image is too large, Maximum filesize allowed is 50kB' ))
        return f

To use this in your form, copy the code into forms.py and add the following to the form definition:


	image= ImageField50KB(
		widget=forms.FileInput,
		initial=BLANK_IMAGE,
	 )

where BLANK_IMAGE has been declared already to point to a file that will be used as default image in case the field is empty.