子类化django choicefield不起作用

时间:2016-04-24 10:34:04

标签: python django subclass choicefield

我正在尝试子类化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不会报告错误,但也不会在呈现中显示内容。

1 个答案:

答案 0 :(得分:1)

不要弄乱Field的类属性,choicesChoiceField实例的属性。改为__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'