From 470c70f876b2fc9c7783a45589f7bfd1c4356078 Mon Sep 17 00:00:00 2001 From: Chris Beaven Date: Fri, 9 Sep 2011 22:57:12 +0000 Subject: [PATCH] Fixes #16664 -- URLField's to_python method fails with ValueError on some urls on python 2.7. Based on patch by zigzag. git-svn-id: http://code.djangoproject.com/svn/django/trunk@16752 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/forms/fields.py | 18 +++++++++++++++--- tests/regressiontests/forms/tests/fields.py | 2 ++ 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/django/forms/fields.py b/django/forms/fields.py index 6fe25a9043..ab83b8b411 100644 --- a/django/forms/fields.py +++ b/django/forms/fields.py @@ -583,9 +583,22 @@ class URLField(CharField): self.validators.append(validators.URLValidator(verify_exists=verify_exists, validator_user_agent=validator_user_agent)) def to_python(self, value): + + def split_url(url): + """ + Returns a list of url parts via ``urlparse.urlsplit`` (or raises a + ``ValidationError`` exception for certain). + """ + try: + return list(urlparse.urlsplit(url)) + except ValueError: + # urlparse.urlsplit can raise a ValueError with some + # misformatted URLs. + raise ValidationError(self.error_messages['invalid']) + value = super(URLField, self).to_python(value) if value: - url_fields = list(urlparse.urlsplit(value)) + url_fields = split_url(value) if not url_fields[0]: # If no URL scheme given, assume http:// url_fields[0] = 'http' @@ -596,8 +609,7 @@ class URLField(CharField): url_fields[2] = '' # Rebuild the url_fields list, since the domain segment may now # contain the path too. - value = urlparse.urlunsplit(url_fields) - url_fields = list(urlparse.urlsplit(value)) + url_fields = split_url(urlparse.urlunsplit(url_fields)) if not url_fields[2]: # the path portion may need to be added before query params url_fields[2] = '/' diff --git a/tests/regressiontests/forms/tests/fields.py b/tests/regressiontests/forms/tests/fields.py index 7cbe2eaccf..5755501e89 100644 --- a/tests/regressiontests/forms/tests/fields.py +++ b/tests/regressiontests/forms/tests/fields.py @@ -587,6 +587,8 @@ class FieldsTests(SimpleTestCase): self.assertEqual(u'http://valid-----hyphens.com/', f.clean('http://valid-----hyphens.com')) self.assertEqual(u'http://some.idn.xyz\xe4\xf6\xfc\xdfabc.domain.com:123/blah', f.clean('http://some.idn.xyzäöüßabc.domain.com:123/blah')) self.assertEqual(u'http://www.example.com/s/http://code.djangoproject.com/ticket/13804', f.clean('www.example.com/s/http://code.djangoproject.com/ticket/13804')) + self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, '[a') + self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://[a') def test_url_regex_ticket11198(self): f = URLField()