diff --git a/django/urls/resolvers.py b/django/urls/resolvers.py index 9f4d84d5a2..5e3e6dea16 100644 --- a/django/urls/resolvers.py +++ b/django/urls/resolvers.py @@ -208,8 +208,6 @@ def _route_to_regex(route, is_endpoint=False): For example, 'foo/' returns '^foo\\/(?P[0-9]+)' and {'pk': }. """ - if not set(route).isdisjoint(string.whitespace): - raise ImproperlyConfigured("URL route '%s' cannot contain whitespace." % route) original_route = route parts = ['^'] converters = {} @@ -218,6 +216,11 @@ def _route_to_regex(route, is_endpoint=False): if not match: parts.append(re.escape(route)) break + elif not set(match.group()).isdisjoint(string.whitespace): + raise ImproperlyConfigured( + "URL route '%s' cannot contain whitespace in angle brackets " + "<…>." % original_route + ) parts.append(re.escape(route[:match.start()])) route = route[match.end():] parameter = match['parameter'] diff --git a/tests/urlpatterns/tests.py b/tests/urlpatterns/tests.py index 54b7e09813..b6b23ade9e 100644 --- a/tests/urlpatterns/tests.py +++ b/tests/urlpatterns/tests.py @@ -1,3 +1,4 @@ +import string import uuid from django.conf.urls import url as conf_url @@ -142,10 +143,19 @@ class SimplifiedURLTests(SimpleTestCase): with self.assertRaisesMessage(ImproperlyConfigured, msg): path('foo//', empty_view) - def test_space_in_route(self): - msg = "URL route 'space/' cannot contain whitespace." - with self.assertRaisesMessage(ImproperlyConfigured, msg): - path('space/', empty_view) + def test_whitespace_in_route(self): + msg = ( + "URL route 'space//extra/' cannot contain " + "whitespace in angle brackets <…>" + ) + for whitespace in string.whitespace: + with self.subTest(repr(whitespace)): + with self.assertRaisesMessage(ImproperlyConfigured, msg % whitespace): + path('space//extra/' % whitespace, empty_view) + # Whitespaces are valid in paths. + p = path('space%s//' % string.whitespace, empty_view) + match = p.resolve('space%s/1/' % string.whitespace) + self.assertEqual(match.kwargs, {'num': 1}) @override_settings(ROOT_URLCONF='urlpatterns.converter_urls')