Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

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
Adrian Holovaty authored January 21, 2007
11  django/newforms/fields.py
@@ -320,10 +320,19 @@ class ChoiceField(Field):
320 320
     def __init__(self, choices=(), required=True, widget=Select, label=None, initial=None):
321 321
         if isinstance(widget, type):
322 322
             widget = widget()
323  
-        widget.choices = choices
324 323
         super(ChoiceField, self).__init__(required, widget, label, initial)
325 324
         self.choices = choices
326 325
 
  326
+    def _get_choices(self):
  327
+        return self._choices
  328
+
  329
+    def _set_choices(self, value):
  330
+        # Setting choices also sets the choices on the widget.
  331
+        self._choices = value
  332
+        self.widget.choices = value
  333
+
  334
+    choices = property(_get_choices, _set_choices)
  335
+
327 336
     def clean(self, value):
328 337
         """
329 338
         Validates that the input is in self.choices.
15  tests/regressiontests/forms/tests.py
@@ -1866,6 +1866,21 @@
1866 1866
 <option value="J">Java</option>
1867 1867
 </select>
1868 1868
 
  1869
+You can set a ChoiceField's choices after the fact.
  1870
+>>> class FrameworkForm(Form):
  1871
+...     name = CharField()
  1872
+...     language = ChoiceField()
  1873
+>>> f = FrameworkForm(auto_id=False)
  1874
+>>> print f['language']
  1875
+<select name="language">
  1876
+</select>
  1877
+>>> f.fields['language'].choices = [('P', 'Python'), ('J', 'Java')]
  1878
+>>> print f['language']
  1879
+<select name="language">
  1880
+<option value="P">Python</option>
  1881
+<option value="J">Java</option>
  1882
+</select>
  1883
+
1869 1884
 Add widget=RadioSelect to use that widget with a ChoiceField.
1870 1885
 >>> class FrameworkForm(Form):
1871 1886
 ...     name = CharField()

0 notes on commit 76f6dd4

Please sign in to comment.
Something went wrong with that request. Please try again.