From 22529d41b26137ac87c5e08a6c19e6e91552756e Mon Sep 17 00:00:00 2001 From: Jannis Leidel Date: Thu, 16 Jun 2011 16:34:38 +0000 Subject: [PATCH] Fixed #15127 -- Properly copy the choices of choice fields. Thanks, dready and Julian Phalip. git-svn-id: http://code.djangoproject.com/svn/django/trunk@16416 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/forms/fields.py | 5 +++++ tests/regressiontests/forms/tests/forms.py | 22 +++++++++++++++++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/django/forms/fields.py b/django/forms/fields.py index 7bee36ee6e..113a5aab22 100644 --- a/django/forms/fields.py +++ b/django/forms/fields.py @@ -657,6 +657,11 @@ class ChoiceField(Field): initial=initial, help_text=help_text, *args, **kwargs) self.choices = choices + def __deepcopy__(self, memo): + result = super(ChoiceField, self).__deepcopy__(memo) + result._choices = copy.deepcopy(self._choices, memo) + return result + def _get_choices(self): return self._choices diff --git a/tests/regressiontests/forms/tests/forms.py b/tests/regressiontests/forms/tests/forms.py index 91a7472cd1..04463cfb2c 100644 --- a/tests/regressiontests/forms/tests/forms.py +++ b/tests/regressiontests/forms/tests/forms.py @@ -771,6 +771,26 @@ class FormsTestCase(TestCase): f = Person(name_max_length=None) self.assertEqual(f['first_name'].field.max_length, f['last_name'].field.max_length, (30, 30)) + # Similarly, choices do not persist from one Form instance to the next. + # Refs #15127. + class Person(Form): + first_name = CharField(required=False) + last_name = CharField(required=False) + gender = ChoiceField(choices=(('f', 'Female'), ('m', 'Male'))) + + def __init__(self, allow_unspec_gender=False, *args, **kwargs): + super(Person, self).__init__(*args, **kwargs) + + if allow_unspec_gender: + self.fields['gender'].choices += (('u', 'Unspecified'),) + + f = Person() + self.assertEqual(f['gender'].field.choices, [('f', 'Female'), ('m', 'Male')]) + f = Person(allow_unspec_gender=True) + self.assertEqual(f['gender'].field.choices, [('f', 'Female'), ('m', 'Male'), ('u', 'Unspecified')]) + f = Person() + self.assertEqual(f['gender'].field.choices, [('f', 'Female'), ('m', 'Male')]) + def test_hidden_widget(self): # HiddenInput widgets are displayed differently in the as_table(), as_ul()) # and as_p() output of a Form -- their verbose names are not displayed, and a @@ -1154,7 +1174,7 @@ class FormsTestCase(TestCase): def test_boundfield_values(self): # It's possible to get to the value which would be used for rendering # the widget for a field by using the BoundField's value method. - + class UserRegistration(Form): username = CharField(max_length=10, initial='djangonaut') password = CharField(widget=PasswordInput)