0

I have 2 model classes class A(models.Model) in app1 and class B(A) in app2 as follows:

#app1/models.py
class CustomImageField(models.ImageField):
    """
    Same as ImageField, but you can specify:
        * max_upload_size - a number indicating the maximum file size allowed for upload.
            5MB - 5242880
    """
    def __init__(self, *args, **kwargs):
        self.max_upload_size = kwargs.pop("max_upload_size")
        super(CustomImageField, self).__init__(*args, **kwargs)

    def clean(self, *args, **kwargs):
        print "inside CustomImageField - clean()"
        data = super(CustomImageField, self).clean(*args, **kwargs)

        file = data.file
        try:
            if file._size > self.max_upload_size:
                raise ValidationError(_('Please keep filesize under %s. Current filesize %s') % (filesizeformat(self.max_upload_size), filesizeformat(file._size)))
        except AttributeError:
            pass

        return data


class A(models.Model):
    logo = CustomImageField(upload_to = upload_path, blank = True, help_text = "Image Files only. Max Size 5MB", max_upload_size = 5242880, verbose_name='Company Logo')
    ...

# app2/models.py
from app1.models import A
class B(A):
    ...

This upload file limit check of CustomImageField is not working, because the clean() is not invoked as I can see from trace. Can you give me a way to call clean method in CustomImageField when I save object of class B.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
attaboyabhipro
  • 1,450
  • 1
  • 17
  • 33
  • You tried calling `full_clean` on an object B before saving? Other way is adding a validator. – Blackeagle52 Mar 30 '15 at 10:04
  • @Blackeagle52 where do I call it. In pre_save signal is it ? Is there a way to call self.full_clean() before save(). Calling in first line of save() doesn't work. – attaboyabhipro Mar 30 '15 at 18:19
  • 1
    I moved the clean() code to clean_fields of model B. Works fine ! if self.logo.size > 5242880: raise ValidationError() – attaboyabhipro Mar 31 '15 at 02:31
  • Congrats to your own solution, but I doubt it is the 'correct' way of doing things. How are you using B? Within a ModelForm? Or just simply in a view or the admin interface? I would prefer just simply adding a validator to a normal ImageField, that should be enough. – Blackeagle52 Mar 31 '15 at 15:23

0 Answers0