Ticket #15127: 15127-form-field-choices-deepcopy.diff

File 15127-form-field-choices-deepcopy.diff, 2.5 KB (added by Julien Phalip, 13 years ago)
  • django/forms/fields.py

    diff --git a/django/forms/fields.py b/django/forms/fields.py
    index e3b4a44..e1f62cf 100644
    a b class ChoiceField(Field):  
    695695                    return True
    696696        return False
    697697
     698    def __deepcopy__(self, memo):
     699        result = super(ChoiceField, self).__deepcopy__(memo)
     700        result._choices = copy.copy(self._choices)
     701        return result
     702
    698703class TypedChoiceField(ChoiceField):
    699704    def __init__(self, *args, **kwargs):
    700705        self.coerce = kwargs.pop('coerce', lambda val: val)
  • tests/regressiontests/forms/tests/forms.py

    diff --git a/tests/regressiontests/forms/tests/forms.py b/tests/regressiontests/forms/tests/forms.py
    index 91a7472..04463cf 100644
    a b class FormsTestCase(TestCase):  
    771771        f = Person(name_max_length=None)
    772772        self.assertEqual(f['first_name'].field.max_length, f['last_name'].field.max_length, (30, 30))
    773773
     774        # Similarly, choices do not persist from one Form instance to the next.
     775        # Refs #15127.
     776        class Person(Form):
     777            first_name = CharField(required=False)
     778            last_name = CharField(required=False)
     779            gender = ChoiceField(choices=(('f', 'Female'), ('m', 'Male')))
     780
     781            def __init__(self, allow_unspec_gender=False, *args, **kwargs):
     782                super(Person, self).__init__(*args, **kwargs)
     783
     784                if allow_unspec_gender:
     785                    self.fields['gender'].choices += (('u', 'Unspecified'),)
     786
     787        f = Person()
     788        self.assertEqual(f['gender'].field.choices, [('f', 'Female'), ('m', 'Male')])
     789        f = Person(allow_unspec_gender=True)
     790        self.assertEqual(f['gender'].field.choices, [('f', 'Female'), ('m', 'Male'), ('u', 'Unspecified')])
     791        f = Person()
     792        self.assertEqual(f['gender'].field.choices, [('f', 'Female'), ('m', 'Male')])
     793
    774794    def test_hidden_widget(self):
    775795        # HiddenInput widgets are displayed differently in the as_table(), as_ul())
    776796        # and as_p() output of a Form -- their verbose names are not displayed, and a
    class FormsTestCase(TestCase):  
    11541174    def test_boundfield_values(self):
    11551175        # It's possible to get to the value which would be used for rendering
    11561176        # the widget for a field by using the BoundField's value method.
    1157  
     1177
    11581178        class UserRegistration(Form):
    11591179            username = CharField(max_length=10, initial='djangonaut')
    11601180            password = CharField(widget=PasswordInput)
Back to Top