我正在尝试子类化ChoiceField,因此我可以在多种形式(DRY)中使用它。例如:
class testField(forms.ChoiceField):
choices = (('a', 'b'), ('c', 'd'))
label = "test"
class testForm(forms.Form):
test = testField()
其他类型的字段作为子类(例如CharField)工作,但是在渲染ChoiceField的子类时,我得到一个模糊的错误:
AttributeError at /..url.../
'testField' object has no attribute '_choices'
在子类中将choices
指定为_choices
不会报告错误,但也不会在呈现中显示内容。
答案 0 :(得分:1)
不要弄乱Field
的类属性,choices
是ChoiceField
实例的属性。改为__init__(...)
,而不是docs:
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'