Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

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
  • Loading branch information...
commit 470c70f876b2fc9c7783a45589f7bfd1c4356078 1 parent c4d8b4c
Chris Beaven SmileyChris authored
18 django/forms/fields.py
View
@@ -583,9 +583,22 @@ def __init__(self, max_length=None, min_length=None, verify_exists=False,
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 @@ def to_python(self, value):
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] = '/'
2  tests/regressiontests/forms/tests/fields.py
View
@@ -587,6 +587,8 @@ def test_urlfield_1(self):
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()
Please sign in to comment.
Something went wrong with that request. Please try again.