diff options
| author | Adrian Holovaty <adrian@holovaty.com> | 2007-01-21 01:29:01 +0000 |
|---|---|---|
| committer | Adrian Holovaty <adrian@holovaty.com> | 2007-01-21 01:29:01 +0000 |
| commit | 76f6dd42cc3c763d9f64c2c8f74f244613ae771b (patch) | |
| tree | 0566af7e6356c2385d5212ed8a09b37febb2a437 | |
| parent | f073318668a40aab280a5e367e725e08538c52e3 (diff) | |
Fixed #3196 -- Fixed inconsistency in setting choices on ChoiceFields dynamically
git-svn-id: http://code.djangoproject.com/svn/django/trunk@4379 bcc190cf-cafb-0310-a4f2-bffc1f526a37
| -rw-r--r-- | django/newforms/fields.py | 11 | ||||
| -rw-r--r-- | tests/regressiontests/forms/tests.py | 15 |
2 files changed, 25 insertions, 1 deletions
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. <option value="J">Java</option> </select> +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'] +<select name="language"> +</select> +>>> f.fields['language'].choices = [('P', 'Python'), ('J', 'Java')] +>>> print f['language'] +<select name="language"> +<option value="P">Python</option> +<option value="J">Java</option> +</select> + Add widget=RadioSelect to use that widget with a ChoiceField. >>> class FrameworkForm(Form): ... name = CharField() |
