Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

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
  • Loading branch information...
commit 76f6dd42cc3c763d9f64c2c8f74f244613ae771b 1 parent f073318
@adrianholovaty adrianholovaty authored
Showing with 25 additions and 1 deletion.
  1. +10 −1 django/newforms/fields.py
  2. +15 −0 tests/regressiontests/forms/tests.py
View
11 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.
View
15 tests/regressiontests/forms/tests.py
@@ -1866,6 +1866,21 @@
<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()
Please sign in to comment.
Something went wrong with that request. Please try again.