Fixed #17125 -- Made it possible to change a `RegexField`'s regular expression validator after it has been initialized. Thanks to Claude Paroz for the report and patch.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@17076 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Julien Phalip 2011-11-07 07:41:24 +00:00
parent b745fc0f4b
commit 90d3697417
2 changed files with 19 additions and 2 deletions

View File

@ -442,10 +442,21 @@ class RegexField(CharField):
error_messages['invalid'] = error_message
kwargs['error_messages'] = error_messages
super(RegexField, self).__init__(max_length, min_length, *args, **kwargs)
self._set_regex(regex)
def _get_regex(self):
return self._regex
def _set_regex(self, regex):
if isinstance(regex, basestring):
regex = re.compile(regex)
self.regex = regex
self.validators.append(validators.RegexValidator(regex=regex))
self._regex = regex
if hasattr(self, '_regex_validator') and self._regex_validator in self.validators:
self.validators.remove(self._regex_validator)
self._regex_validator = validators.RegexValidator(regex=regex)
self.validators.append(self._regex_validator)
regex = property(_get_regex, _set_regex)
class EmailField(CharField):
default_error_messages = {

View File

@ -493,6 +493,12 @@ class FieldsTests(SimpleTestCase):
self.assertRaisesMessage(ValidationError, "[u'Ensure this value has at most 10 characters (it has 11).']", f.clean, '12345678901')
self.assertRaisesMessage(ValidationError, "[u'Enter a valid value.']", f.clean, '12345a')
def test_change_regex_after_init(self):
f = RegexField('^[a-z]+$')
f.regex = '^\d+$'
self.assertEqual(u'1234', f.clean('1234'))
self.assertRaisesMessage(ValidationError, "[u'Enter a valid value.']", f.clean, 'abcd')
# EmailField ##################################################################
def test_emailfield_1(self):