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
This commit is contained in:
parent
c4d8b4c0b2
commit
470c70f876
|
@ -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] = '/'
|
||||
|
|
|
@ -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()
|
||||
|
|
Loading…
Reference in New Issue