1

モデルでUSSocialSecurityNumberFieldを使用したいと考えています。正確には、モデルに CharField を使用しても問題ありませんが、そのモデルに基づいてモデルフォームに USSocialSecurityNumberField を挿入したいと考えています。

モデルフィールドをサブクラス化する以外に、モデルフィールドのデフォルトのフォームフィールドをオーバーライドする方法はありますか? 私は次のようなことを意味します:

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

これは、1 回限りの必要性に対する最も簡単な解決策です。

PS。モデルフィールドとフォームフィールドの他の組み合わせにも興味があるので、サブクラス化は厄介な解決策です..

4

2 に答える 2

2

それがまさにあなたが探しているものかどうかはわかりません。フォームフィールドの値を検証することに関心がある場合は、バリデーターを使用できます。

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])
于 2012-10-26T14:53:35.103 に答える
1

このような引数は、FieldにもModelFieldにも存在しません。しかし、サブクラス化はそれほど難しくないはずです。これに沿った何かがうまくいくはずだと私は信じています。

class MyModelField(models.Field):
    def formfield(self, **kwargs):
        kwargs['form_class'] = forms.USSocialSecurityNumberField
        return super(MyModelField, self).formfield(**kwargs)
于 2012-10-26T14:57:41.633 に答える