当我继承另一个类中包含自定义字段的类时,不会调用Django自定义模型字段clean()。

2024-04-19 20:58:11 发布

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

我有两个模特班(模型。模型)附录1中的和附录2中的B(A)如下所示:

#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):
    ...

CustomImageField的上载文件限制检查不起作用,因为从跟踪中可以看到,clean()没有被调用。当我保存B类的对象时,你能给我一个在CustomImageField中调用clean方法的方法吗


Tags: py模型selfcleandatasizemodelsargs