2016-04-24 3 views
1

ChoiceFieldをサブクラス化して複数のフォーム(DRY)で使用できるようにしようとしています。たとえば:django choicefieldのサブクラス化が機能しない

_choicesとして choicesを指定
AttributeError at /..url.../ 
'testField' object has no attribute '_choices' 

class testField(forms.ChoiceField): 
    choices = (('a', 'b'), ('c', 'd')) 
    label = "test" 

class testForm(forms.Form): 
    test = testField() 

フィールドの他のタイプのChoiceFieldのサブクラスをレンダリングするときしかし、私はあいまいなエラーを取得し、(例えばCharFieldですなど)のサブクラスとして働きますサブクラスはエラーを報告しませんが、レンダリングの内容を表示しません。

答えて

1

Fieldのクラスプロパティを使用しないでください。choicesは、ChoiceFieldインスタンスの属性です。 docsに助言として、代わりに__init__(...)をオーバーライドします:完璧に動作

class TestField(ChoiceField): 
    def __init__(self, *args, **kwargs): 
     kwargs['choices'] = ((1, 'a'), (2, 'b')) 
     kwargs['label'] = "test" 
     super(TestField, self).__init__(*args, **kwargs) 

class TestForm(Form): 
    test = TestField() 

f = TestForm() 

f.fields['test'].choices 
> [(1, 'a'), (2, 'b')] 

f.fields['test'].label 
> 'test' 
+0

- 感謝を – dwagon

関連する問題