diff --git a/django/newforms/fields.py b/django/newforms/fields.py index a72ac39d5c..3ba4f77c22 100644 --- a/django/newforms/fields.py +++ b/django/newforms/fields.py @@ -320,10 +320,19 @@ class ChoiceField(Field): def __init__(self, choices=(), required=True, widget=Select, label=None, initial=None): if isinstance(widget, type): widget = widget() - widget.choices = choices super(ChoiceField, self).__init__(required, widget, label, initial) self.choices = choices + def _get_choices(self): + return self._choices + + def _set_choices(self, value): + # Setting choices also sets the choices on the widget. + self._choices = value + self.widget.choices = value + + choices = property(_get_choices, _set_choices) + def clean(self, value): """ Validates that the input is in self.choices. diff --git a/tests/regressiontests/forms/tests.py b/tests/regressiontests/forms/tests.py index b1425bef6d..5f003711dc 100644 --- a/tests/regressiontests/forms/tests.py +++ b/tests/regressiontests/forms/tests.py @@ -1866,6 +1866,21 @@ defined on the Field, not the ones defined on the Widget. +You can set a ChoiceField's choices after the fact. +>>> class FrameworkForm(Form): +... name = CharField() +... language = ChoiceField() +>>> f = FrameworkForm(auto_id=False) +>>> print f['language'] + +>>> f.fields['language'].choices = [('P', 'Python'), ('J', 'Java')] +>>> print f['language'] + + Add widget=RadioSelect to use that widget with a ChoiceField. >>> class FrameworkForm(Form): ... name = CharField()