我正在尝试对 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
不会报错,但渲染中也不会显示内容。
最佳答案
不要弄乱 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'
关于python - 子类化 django choicefield 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36821980/