我试图对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不会报告错误,但也不会显示呈现中的内容。
发布于 2016-04-24 12:57:56
不要弄乱Field的类属性,choices是ChoiceField实例的一个属性。
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'https://stackoverflow.com/questions/36821980
复制相似问题