首页 文章

模型字段的自定义表单字段

提问于
浏览
1

我想在模型中使用USSocialSecurityNumberField . 确切地说,我可以在模型中使用CharField,但我希望将USSocialSecurityNumberField注入基于该模型的模型 .

有没有办法覆盖模型字段的默认表单字段,而不是subclassing model fields?我的意思是:

ssn = models.CharField(max_length=11, formfield=USSocialSecurityNumberField)

这对于一次性需求来说是最简单的解决方案 .

PS . 我也对模型字段和表单字段的其他组合感兴趣,所以子类化是一个烦人的解决方案..

2 回答

  • 2

    这种论证既不存在于Field也不存在于ModelField中 . 但是子类化不应该太难,我相信这应该有用:

    class MyModelField(models.Field):
        def formfield(self, **kwargs):
            kwargs['form_class'] = forms.USSocialSecurityNumberField
            return super(MyModelField, self).formfield(**kwargs)
    
  • 1

    我不确定这正是你要找的 . 如果您有兴趣验证表单域的值,可以使用验证器:

    def validate_USSocialSecurityNumberField(myNumber):
        # here goes the validation algorithm which will raise a ValidationError 
        # if the number is not in the correct format
        # and of course you will catch the exception
        # except ValueError:
        #     raise ValidationError(u'"%s" is not in the correct format!' % myNumber)
    

    你的模型可能看起来像:

    ssn = models.CharField(max_length=11, validators = [validate_USSocialSecurityNumberField])
    

相关问题