Ticket #17125: 17125.1.diff

File 17125.1.diff, 2.0 KB (added by Claude Paroz, 13 years ago)

Allow modification of regex after RegexField init

  • django/forms/fields.py

    diff --git a/django/forms/fields.py b/django/forms/fields.py
    index 8e727b4..145c2dc 100644
    a b class RegexField(CharField):  
    441441            error_messages['invalid'] = error_message
    442442            kwargs['error_messages'] = error_messages
    443443        super(RegexField, self).__init__(max_length, min_length, *args, **kwargs)
     444        self._set_regex(regex)
     445
     446    def _get_regex(self):
     447        return self._regex
     448
     449    def _set_regex(self, regex):
    444450        if isinstance(regex, basestring):
    445451            regex = re.compile(regex)
    446         self.regex = regex
    447         self.validators.append(validators.RegexValidator(regex=regex))
     452        self._regex = regex
     453        if hasattr(self, '_regex_validator') and self._regex_validator in self.validators:
     454            self.validators.remove(self._regex_validator)
     455        self._regex_validator = validators.RegexValidator(regex=regex)
     456        self.validators.append(self._regex_validator)
     457
     458    regex = property(_get_regex, _set_regex)
    448459
    449460class EmailField(CharField):
    450461    default_error_messages = {
  • tests/regressiontests/forms/tests/fields.py

    diff --git a/tests/regressiontests/forms/tests/fields.py b/tests/regressiontests/forms/tests/fields.py
    index d37ad5e..50822fa 100644
    a b class FieldsTests(SimpleTestCase):  
    489489        self.assertRaisesMessage(ValidationError, "[u'Ensure this value has at most 10 characters (it has 11).']", f.clean, '12345678901')
    490490        self.assertRaisesMessage(ValidationError, "[u'Enter a valid value.']", f.clean, '12345a')
    491491
     492    def test_change_regex_after_init(self):
     493        f = RegexField('^[a-z]+$')
     494        f.regex = '^\d+$'
     495        self.assertEqual(u'1234', f.clean('1234'))
     496        self.assertRaisesMessage(ValidationError, "[u'Enter a valid value.']", f.clean, 'abcd')
     497
    492498    # EmailField ##################################################################
    493499
    494500    def test_emailfield_1(self):
Back to Top