如何在django中为继承的模型属性创建通用的modelform字段验证器?

时间:2015-01-10 08:30:07

标签: python regex django validation

我有一个父模型:

class AbstractAddress(models.Model):
    name = models.CharField(max_length=100,verbose_name='Name')
    address1 = models.CharField(max_length=100,null=True,blank=True)
    city = models.CharField(max_length=100,null=True,blank=True)
    phone = models.CharField(max_length=10,null=True,blank=True)
    pincode = models.IntegerField(null=True,blank=True, default=0)

    class Meta:
          abstract = True

我继承这个模型来创建供应商,客户端,员工模型。现在在管理员ModelForm:

pincode = CharField(widget=TextInput(attrs={'type':'number'}),
                    validators=[RegexValidator(regex='^.{6}$',message='Pincode can have 6 digits')],
                    required=False, min_length=6)

phone = CharField(widget=TextInput(attrs={'type':'number',
                                          'size':'10'}),
                  validators=[RegexValidator(regex='^.{10}$', message='Phone can have 10 digits')],
                  required=False, min_length=10)

这段代码我不想为上面提到的模型的每个模型编写代码。我怎样才能使用DRY?

1 个答案:

答案 0 :(得分:1)

我已将项目中的验证定义在与settings.py相同的文件夹中,并将验证方法定义为:

def validated_pincode():
    pincode = CharField(widget=TextInput(attrs={'type':'number'}),
                  validators=[RegexValidator(regex='^.{6}$',message='Pincode can have 6 digits')],
                    required=False, min_length=6)
    return pincode

以modeladmin形式我称之为方法:

pincode = validated_pincode()