1

I'm trying to subclass the ChoiceField so I can use it in multiple forms (DRY). For example:

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

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

Other types of Fields work as subclasses (such as CharField), however when rendering the subclass of ChoiceField I get an obscure error:

AttributeError at /..url.../
'testField' object has no attribute '_choices'

Specifying the choices as _choices in the subclass doesn't report the error, but nor does it display the contents in the rendering.

dwagon
  • 501
  • 3
  • 9

1 Answers1

1

Don't mess with the Field's class properties, choices is an attribute of a ChoiceField instance. Override __init__(...) instead, as advised in the 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'
user2390182
  • 72,016
  • 6
  • 67
  • 89