You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

resolvers.py 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  1. """
  2. This module converts requested URLs to callback view functions.
  3. URLResolver is the main class here. Its resolve() method takes a URL (as
  4. a string) and returns a ResolverMatch object which provides access to all
  5. attributes of the resolved URL match.
  6. """
  7. import functools
  8. import inspect
  9. import re
  10. import threading
  11. from importlib import import_module
  12. from urllib.parse import quote
  13. from django.conf import settings
  14. from django.core.checks import Error, Warning
  15. from django.core.checks.urls import check_resolver
  16. from django.core.exceptions import ImproperlyConfigured, ViewDoesNotExist
  17. from django.utils.datastructures import MultiValueDict
  18. from django.utils.functional import cached_property
  19. from django.utils.http import RFC3986_SUBDELIMS, escape_leading_slashes
  20. from django.utils.regex_helper import normalize
  21. from django.utils.translation import get_language
  22. from .converters import get_converter
  23. from .exceptions import NoReverseMatch, Resolver404
  24. from .utils import get_callable
  25. class ResolverMatch:
  26. def __init__(self, func, args, kwargs, url_name=None, app_names=None, namespaces=None, route=None):
  27. self.func = func
  28. self.args = args
  29. self.kwargs = kwargs
  30. self.url_name = url_name
  31. self.route = route
  32. # If a URLRegexResolver doesn't have a namespace or app_name, it passes
  33. # in an empty value.
  34. self.app_names = [x for x in app_names if x] if app_names else []
  35. self.app_name = ':'.join(self.app_names)
  36. self.namespaces = [x for x in namespaces if x] if namespaces else []
  37. self.namespace = ':'.join(self.namespaces)
  38. if not hasattr(func, '__name__'):
  39. # A class-based view
  40. self._func_path = func.__class__.__module__ + '.' + func.__class__.__name__
  41. else:
  42. # A function-based view
  43. self._func_path = func.__module__ + '.' + func.__name__
  44. view_path = url_name or self._func_path
  45. self.view_name = ':'.join(self.namespaces + [view_path])
  46. def __getitem__(self, index):
  47. return (self.func, self.args, self.kwargs)[index]
  48. def __repr__(self):
  49. return "ResolverMatch(func=%s, args=%s, kwargs=%s, url_name=%s, app_names=%s, namespaces=%s, route=%s)" % (
  50. self._func_path, self.args, self.kwargs, self.url_name,
  51. self.app_names, self.namespaces, self.route,
  52. )
  53. @functools.lru_cache(maxsize=None)
  54. def get_resolver(urlconf=None):
  55. if urlconf is None:
  56. urlconf = settings.ROOT_URLCONF
  57. return URLResolver(RegexPattern(r'^/'), urlconf)
  58. @functools.lru_cache(maxsize=None)
  59. def get_ns_resolver(ns_pattern, resolver, converters):
  60. # Build a namespaced resolver for the given parent URLconf pattern.
  61. # This makes it possible to have captured parameters in the parent
  62. # URLconf pattern.
  63. pattern = RegexPattern(ns_pattern)
  64. pattern.converters = dict(converters)
  65. ns_resolver = URLResolver(pattern, resolver.url_patterns)
  66. return URLResolver(RegexPattern(r'^/'), [ns_resolver])
  67. class LocaleRegexDescriptor:
  68. def __init__(self, attr):
  69. self.attr = attr
  70. def __get__(self, instance, cls=None):
  71. """
  72. Return a compiled regular expression based on the active language.
  73. """
  74. if instance is None:
  75. return self
  76. # As a performance optimization, if the given regex string is a regular
  77. # string (not a lazily-translated string proxy), compile it once and
  78. # avoid per-language compilation.
  79. pattern = getattr(instance, self.attr)
  80. if isinstance(pattern, str):
  81. instance.__dict__['regex'] = instance._compile(pattern)
  82. return instance.__dict__['regex']
  83. language_code = get_language()
  84. if language_code not in instance._regex_dict:
  85. instance._regex_dict[language_code] = instance._compile(str(pattern))
  86. return instance._regex_dict[language_code]
  87. class CheckURLMixin:
  88. def describe(self):
  89. """
  90. Format the URL pattern for display in warning messages.
  91. """
  92. description = "'{}'".format(self)
  93. if self.name:
  94. description += " [name='{}']".format(self.name)
  95. return description
  96. def _check_pattern_startswith_slash(self):
  97. """
  98. Check that the pattern does not begin with a forward slash.
  99. """
  100. regex_pattern = self.regex.pattern
  101. if not settings.APPEND_SLASH:
  102. # Skip check as it can be useful to start a URL pattern with a slash
  103. # when APPEND_SLASH=False.
  104. return []
  105. if regex_pattern.startswith(('/', '^/', '^\\/')) and not regex_pattern.endswith('/'):
  106. warning = Warning(
  107. "Your URL pattern {} has a route beginning with a '/'. Remove this "
  108. "slash as it is unnecessary. If this pattern is targeted in an "
  109. "include(), ensure the include() pattern has a trailing '/'.".format(
  110. self.describe()
  111. ),
  112. id="urls.W002",
  113. )
  114. return [warning]
  115. else:
  116. return []
  117. class RegexPattern(CheckURLMixin):
  118. regex = LocaleRegexDescriptor('_regex')
  119. def __init__(self, regex, name=None, is_endpoint=False):
  120. self._regex = regex
  121. self._regex_dict = {}
  122. self._is_endpoint = is_endpoint
  123. self.name = name
  124. self.converters = {}
  125. def match(self, path):
  126. match = self.regex.search(path)
  127. if match:
  128. # If there are any named groups, use those as kwargs, ignoring
  129. # non-named groups. Otherwise, pass all non-named arguments as
  130. # positional arguments.
  131. kwargs = match.groupdict()
  132. args = () if kwargs else match.groups()
  133. return path[match.end():], args, kwargs
  134. return None
  135. def check(self):
  136. warnings = []
  137. warnings.extend(self._check_pattern_startswith_slash())
  138. if not self._is_endpoint:
  139. warnings.extend(self._check_include_trailing_dollar())
  140. return warnings
  141. def _check_include_trailing_dollar(self):
  142. regex_pattern = self.regex.pattern
  143. if regex_pattern.endswith('$') and not regex_pattern.endswith(r'\$'):
  144. return [Warning(
  145. "Your URL pattern {} uses include with a route ending with a '$'. "
  146. "Remove the dollar from the route to avoid problems including "
  147. "URLs.".format(self.describe()),
  148. id='urls.W001',
  149. )]
  150. else:
  151. return []
  152. def _compile(self, regex):
  153. """Compile and return the given regular expression."""
  154. try:
  155. return re.compile(regex)
  156. except re.error as e:
  157. raise ImproperlyConfigured(
  158. '"%s" is not a valid regular expression: %s' % (regex, e)
  159. )
  160. def __str__(self):
  161. return str(self._regex)
  162. _PATH_PARAMETER_COMPONENT_RE = re.compile(
  163. r'<(?:(?P<converter>[^>:]+):)?(?P<parameter>\w+)>'
  164. )
  165. def _route_to_regex(route, is_endpoint=False):
  166. """
  167. Convert a path pattern into a regular expression. Return the regular
  168. expression and a dictionary mapping the capture names to the converters.
  169. For example, 'foo/<int:pk>' returns '^foo\\/(?P<pk>[0-9]+)'
  170. and {'pk': <django.urls.converters.IntConverter>}.
  171. """
  172. original_route = route
  173. parts = ['^']
  174. converters = {}
  175. while True:
  176. match = _PATH_PARAMETER_COMPONENT_RE.search(route)
  177. if not match:
  178. parts.append(re.escape(route))
  179. break
  180. parts.append(re.escape(route[:match.start()]))
  181. route = route[match.end():]
  182. parameter = match.group('parameter')
  183. if not parameter.isidentifier():
  184. raise ImproperlyConfigured(
  185. "URL route '%s' uses parameter name %r which isn't a valid "
  186. "Python identifier." % (original_route, parameter)
  187. )
  188. raw_converter = match.group('converter')
  189. if raw_converter is None:
  190. # If a converter isn't specified, the default is `str`.
  191. raw_converter = 'str'
  192. try:
  193. converter = get_converter(raw_converter)
  194. except KeyError as e:
  195. raise ImproperlyConfigured(
  196. "URL route '%s' uses invalid converter %s." % (original_route, e)
  197. )
  198. converters[parameter] = converter
  199. parts.append('(?P<' + parameter + '>' + converter.regex + ')')
  200. if is_endpoint:
  201. parts.append('$')
  202. return ''.join(parts), converters
  203. class RoutePattern(CheckURLMixin):
  204. regex = LocaleRegexDescriptor('_route')
  205. def __init__(self, route, name=None, is_endpoint=False):
  206. self._route = route
  207. self._regex_dict = {}
  208. self._is_endpoint = is_endpoint
  209. self.name = name
  210. self.converters = _route_to_regex(str(route), is_endpoint)[1]
  211. def match(self, path):
  212. match = self.regex.search(path)
  213. if match:
  214. # RoutePattern doesn't allow non-named groups so args are ignored.
  215. kwargs = match.groupdict()
  216. for key, value in kwargs.items():
  217. converter = self.converters[key]
  218. try:
  219. kwargs[key] = converter.to_python(value)
  220. except ValueError:
  221. return None
  222. return path[match.end():], (), kwargs
  223. return None
  224. def check(self):
  225. warnings = self._check_pattern_startswith_slash()
  226. route = self._route
  227. if '(?P<' in route or route.startswith('^') or route.endswith('$'):
  228. warnings.append(Warning(
  229. "Your URL pattern {} has a route that contains '(?P<', begins "
  230. "with a '^', or ends with a '$'. This was likely an oversight "
  231. "when migrating to django.urls.path().".format(self.describe()),
  232. id='2_0.W001',
  233. ))
  234. return warnings
  235. def _compile(self, route):
  236. return re.compile(_route_to_regex(route, self._is_endpoint)[0])
  237. def __str__(self):
  238. return str(self._route)
  239. class LocalePrefixPattern:
  240. def __init__(self, prefix_default_language=True):
  241. self.prefix_default_language = prefix_default_language
  242. self.converters = {}
  243. @property
  244. def regex(self):
  245. # This is only used by reverse() and cached in _reverse_dict.
  246. return re.compile(self.language_prefix)
  247. @property
  248. def language_prefix(self):
  249. language_code = get_language() or settings.LANGUAGE_CODE
  250. if language_code == settings.LANGUAGE_CODE and not self.prefix_default_language:
  251. return ''
  252. else:
  253. return '%s/' % language_code
  254. def match(self, path):
  255. language_prefix = self.language_prefix
  256. if path.startswith(language_prefix):
  257. return path[len(language_prefix):], (), {}
  258. return None
  259. def check(self):
  260. return []
  261. def describe(self):
  262. return "'{}'".format(self)
  263. def __str__(self):
  264. return self.language_prefix
  265. class URLPattern:
  266. def __init__(self, pattern, callback, default_args=None, name=None):
  267. self.pattern = pattern
  268. self.callback = callback # the view
  269. self.default_args = default_args or {}
  270. self.name = name
  271. def __repr__(self):
  272. return '<%s %s>' % (self.__class__.__name__, self.pattern.describe())
  273. def check(self):
  274. warnings = self._check_pattern_name()
  275. warnings.extend(self.pattern.check())
  276. return warnings
  277. def _check_pattern_name(self):
  278. """
  279. Check that the pattern name does not contain a colon.
  280. """
  281. if self.pattern.name is not None and ":" in self.pattern.name:
  282. warning = Warning(
  283. "Your URL pattern {} has a name including a ':'. Remove the colon, to "
  284. "avoid ambiguous namespace references.".format(self.pattern.describe()),
  285. id="urls.W003",
  286. )
  287. return [warning]
  288. else:
  289. return []
  290. def resolve(self, path):
  291. match = self.pattern.match(path)
  292. if match:
  293. new_path, args, kwargs = match
  294. # Pass any extra_kwargs as **kwargs.
  295. kwargs.update(self.default_args)
  296. return ResolverMatch(self.callback, args, kwargs, self.pattern.name, route=str(self.pattern))
  297. @cached_property
  298. def lookup_str(self):
  299. """
  300. A string that identifies the view (e.g. 'path.to.view_function' or
  301. 'path.to.ClassBasedView').
  302. """
  303. callback = self.callback
  304. if isinstance(callback, functools.partial):
  305. callback = callback.func
  306. if not hasattr(callback, '__name__'):
  307. return callback.__module__ + "." + callback.__class__.__name__
  308. return callback.__module__ + "." + callback.__qualname__
  309. class URLResolver:
  310. def __init__(self, pattern, urlconf_name, default_kwargs=None, app_name=None, namespace=None):
  311. self.pattern = pattern
  312. # urlconf_name is the dotted Python path to the module defining
  313. # urlpatterns. It may also be an object with an urlpatterns attribute
  314. # or urlpatterns itself.
  315. self.urlconf_name = urlconf_name
  316. self.callback = None
  317. self.default_kwargs = default_kwargs or {}
  318. self.namespace = namespace
  319. self.app_name = app_name
  320. self._reverse_dict = {}
  321. self._namespace_dict = {}
  322. self._app_dict = {}
  323. # set of dotted paths to all functions and classes that are used in
  324. # urlpatterns
  325. self._callback_strs = set()
  326. self._populated = False
  327. self._local = threading.local()
  328. self._urlconf_lock = threading.Lock()
  329. def __repr__(self):
  330. if isinstance(self.urlconf_name, list) and self.urlconf_name:
  331. # Don't bother to output the whole list, it can be huge
  332. urlconf_repr = '<%s list>' % self.urlconf_name[0].__class__.__name__
  333. else:
  334. urlconf_repr = repr(self.urlconf_name)
  335. return '<%s %s (%s:%s) %s>' % (
  336. self.__class__.__name__, urlconf_repr, self.app_name,
  337. self.namespace, self.pattern.describe(),
  338. )
  339. def check(self):
  340. messages = []
  341. for pattern in self.url_patterns:
  342. messages.extend(check_resolver(pattern))
  343. messages.extend(self._check_custom_error_handlers())
  344. return messages or self.pattern.check()
  345. def _check_custom_error_handlers(self):
  346. messages = []
  347. # All handlers take (request, exception) arguments except handler500
  348. # which takes (request).
  349. for status_code, num_parameters in [(400, 2), (403, 2), (404, 2), (500, 1)]:
  350. try:
  351. handler, param_dict = self.resolve_error_handler(status_code)
  352. except (ImportError, ViewDoesNotExist) as e:
  353. path = getattr(self.urlconf_module, 'handler%s' % status_code)
  354. msg = (
  355. "The custom handler{status_code} view '{path}' could not be imported."
  356. ).format(status_code=status_code, path=path)
  357. messages.append(Error(msg, hint=str(e), id='urls.E008'))
  358. continue
  359. signature = inspect.signature(handler)
  360. args = [None] * num_parameters
  361. try:
  362. signature.bind(*args)
  363. except TypeError:
  364. msg = (
  365. "The custom handler{status_code} view '{path}' does not "
  366. "take the correct number of arguments ({args})."
  367. ).format(
  368. status_code=status_code,
  369. path=handler.__module__ + '.' + handler.__qualname__,
  370. args='request, exception' if num_parameters == 2 else 'request',
  371. )
  372. messages.append(Error(msg, id='urls.E007'))
  373. return messages
  374. def _populate(self):
  375. # Short-circuit if called recursively in this thread to prevent
  376. # infinite recursion. Concurrent threads may call this at the same
  377. # time and will need to continue, so set 'populating' on a
  378. # thread-local variable.
  379. if getattr(self._local, 'populating', False):
  380. return
  381. try:
  382. self._local.populating = True
  383. lookups = MultiValueDict()
  384. namespaces = {}
  385. apps = {}
  386. language_code = get_language()
  387. for url_pattern in reversed(self.url_patterns):
  388. p_pattern = url_pattern.pattern.regex.pattern
  389. if p_pattern.startswith('^'):
  390. p_pattern = p_pattern[1:]
  391. if isinstance(url_pattern, URLPattern):
  392. self._callback_strs.add(url_pattern.lookup_str)
  393. bits = normalize(url_pattern.pattern.regex.pattern)
  394. lookups.appendlist(
  395. url_pattern.callback,
  396. (bits, p_pattern, url_pattern.default_args, url_pattern.pattern.converters)
  397. )
  398. if url_pattern.name is not None:
  399. lookups.appendlist(
  400. url_pattern.name,
  401. (bits, p_pattern, url_pattern.default_args, url_pattern.pattern.converters)
  402. )
  403. else: # url_pattern is a URLResolver.
  404. url_pattern._populate()
  405. if url_pattern.app_name:
  406. apps.setdefault(url_pattern.app_name, []).append(url_pattern.namespace)
  407. namespaces[url_pattern.namespace] = (p_pattern, url_pattern)
  408. else:
  409. for name in url_pattern.reverse_dict:
  410. for matches, pat, defaults, converters in url_pattern.reverse_dict.getlist(name):
  411. new_matches = normalize(p_pattern + pat)
  412. lookups.appendlist(
  413. name,
  414. (
  415. new_matches,
  416. p_pattern + pat,
  417. {**defaults, **url_pattern.default_kwargs},
  418. {**self.pattern.converters, **url_pattern.pattern.converters, **converters}
  419. )
  420. )
  421. for namespace, (prefix, sub_pattern) in url_pattern.namespace_dict.items():
  422. current_converters = url_pattern.pattern.converters
  423. sub_pattern.pattern.converters.update(current_converters)
  424. namespaces[namespace] = (p_pattern + prefix, sub_pattern)
  425. for app_name, namespace_list in url_pattern.app_dict.items():
  426. apps.setdefault(app_name, []).extend(namespace_list)
  427. self._callback_strs.update(url_pattern._callback_strs)
  428. self._namespace_dict[language_code] = namespaces
  429. self._app_dict[language_code] = apps
  430. self._reverse_dict[language_code] = lookups
  431. self._populated = True
  432. finally:
  433. self._local.populating = False
  434. @property
  435. def reverse_dict(self):
  436. language_code = get_language()
  437. if language_code not in self._reverse_dict:
  438. self._populate()
  439. return self._reverse_dict[language_code]
  440. @property
  441. def namespace_dict(self):
  442. language_code = get_language()
  443. if language_code not in self._namespace_dict:
  444. self._populate()
  445. return self._namespace_dict[language_code]
  446. @property
  447. def app_dict(self):
  448. language_code = get_language()
  449. if language_code not in self._app_dict:
  450. self._populate()
  451. return self._app_dict[language_code]
  452. @staticmethod
  453. def _join_route(route1, route2):
  454. """Join two routes, without the starting ^ in the second route."""
  455. if not route1:
  456. return route2
  457. if route2.startswith('^'):
  458. route2 = route2[1:]
  459. return route1 + route2
  460. def _is_callback(self, name):
  461. if not self._populated:
  462. self._populate()
  463. return name in self._callback_strs
  464. def resolve(self, path):
  465. path = str(path) # path may be a reverse_lazy object
  466. tried = []
  467. match = self.pattern.match(path)
  468. if match:
  469. new_path, args, kwargs = match
  470. for pattern in self.url_patterns:
  471. try:
  472. sub_match = pattern.resolve(new_path)
  473. except Resolver404 as e:
  474. sub_tried = e.args[0].get('tried')
  475. if sub_tried is not None:
  476. tried.extend([pattern] + t for t in sub_tried)
  477. else:
  478. tried.append([pattern])
  479. else:
  480. if sub_match:
  481. # Merge captured arguments in match with submatch
  482. sub_match_dict = {**kwargs, **self.default_kwargs}
  483. # Update the sub_match_dict with the kwargs from the sub_match.
  484. sub_match_dict.update(sub_match.kwargs)
  485. # If there are *any* named groups, ignore all non-named groups.
  486. # Otherwise, pass all non-named arguments as positional arguments.
  487. sub_match_args = sub_match.args
  488. if not sub_match_dict:
  489. sub_match_args = args + sub_match.args
  490. current_route = '' if isinstance(pattern, URLPattern) else str(pattern.pattern)
  491. return ResolverMatch(
  492. sub_match.func,
  493. sub_match_args,
  494. sub_match_dict,
  495. sub_match.url_name,
  496. [self.app_name] + sub_match.app_names,
  497. [self.namespace] + sub_match.namespaces,
  498. self._join_route(current_route, sub_match.route),
  499. )
  500. tried.append([pattern])
  501. raise Resolver404({'tried': tried, 'path': new_path})
  502. raise Resolver404({'path': path})
  503. @cached_property
  504. def urlconf_module(self):
  505. # import_module is not thread safe if the module throws an exception
  506. # during import, and can return an empty module object in Python < 3.6
  507. # (see https://bugs.python.org/issue36284).
  508. with self._urlconf_lock:
  509. if isinstance(self.urlconf_name, str):
  510. return import_module(self.urlconf_name)
  511. else:
  512. return self.urlconf_name
  513. @cached_property
  514. def url_patterns(self):
  515. # urlconf_module might be a valid set of patterns, so we default to it
  516. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  517. try:
  518. iter(patterns)
  519. except TypeError:
  520. msg = (
  521. "The included URLconf '{name}' does not appear to have any "
  522. "patterns in it. If you see valid patterns in the file then "
  523. "the issue is probably caused by a circular import."
  524. )
  525. raise ImproperlyConfigured(msg.format(name=self.urlconf_name))
  526. return patterns
  527. def resolve_error_handler(self, view_type):
  528. callback = getattr(self.urlconf_module, 'handler%s' % view_type, None)
  529. if not callback:
  530. # No handler specified in file; use lazy import, since
  531. # django.conf.urls imports this file.
  532. from django.conf import urls
  533. callback = getattr(urls, 'handler%s' % view_type)
  534. return get_callable(callback), {}
  535. def reverse(self, lookup_view, *args, **kwargs):
  536. return self._reverse_with_prefix(lookup_view, '', *args, **kwargs)
  537. def _reverse_with_prefix(self, lookup_view, _prefix, *args, **kwargs):
  538. if args and kwargs:
  539. raise ValueError("Don't mix *args and **kwargs in call to reverse()!")
  540. if not self._populated:
  541. self._populate()
  542. possibilities = self.reverse_dict.getlist(lookup_view)
  543. for possibility, pattern, defaults, converters in possibilities:
  544. for result, params in possibility:
  545. if args:
  546. if len(args) != len(params):
  547. continue
  548. candidate_subs = dict(zip(params, args))
  549. else:
  550. if set(kwargs).symmetric_difference(params).difference(defaults):
  551. continue
  552. if any(kwargs.get(k, v) != v for k, v in defaults.items()):
  553. continue
  554. candidate_subs = kwargs
  555. # Convert the candidate subs to text using Converter.to_url().
  556. text_candidate_subs = {}
  557. for k, v in candidate_subs.items():
  558. if k in converters:
  559. text_candidate_subs[k] = converters[k].to_url(v)
  560. else:
  561. text_candidate_subs[k] = str(v)
  562. # WSGI provides decoded URLs, without %xx escapes, and the URL
  563. # resolver operates on such URLs. First substitute arguments
  564. # without quoting to build a decoded URL and look for a match.
  565. # Then, if we have a match, redo the substitution with quoted
  566. # arguments in order to return a properly encoded URL.
  567. candidate_pat = _prefix.replace('%', '%%') + result
  568. if re.search('^%s%s' % (re.escape(_prefix), pattern), candidate_pat % text_candidate_subs):
  569. # safe characters from `pchar` definition of RFC 3986
  570. url = quote(candidate_pat % text_candidate_subs, safe=RFC3986_SUBDELIMS + '/~:@')
  571. # Don't allow construction of scheme relative urls.
  572. return escape_leading_slashes(url)
  573. # lookup_view can be URL name or callable, but callables are not
  574. # friendly in error messages.
  575. m = getattr(lookup_view, '__module__', None)
  576. n = getattr(lookup_view, '__name__', None)
  577. if m is not None and n is not None:
  578. lookup_view_s = "%s.%s" % (m, n)
  579. else:
  580. lookup_view_s = lookup_view
  581. patterns = [pattern for (_, pattern, _, _) in possibilities]
  582. if patterns:
  583. if args:
  584. arg_msg = "arguments '%s'" % (args,)
  585. elif kwargs:
  586. arg_msg = "keyword arguments '%s'" % (kwargs,)
  587. else:
  588. arg_msg = "no arguments"
  589. msg = (
  590. "Reverse for '%s' with %s not found. %d pattern(s) tried: %s" %
  591. (lookup_view_s, arg_msg, len(patterns), patterns)
  592. )
  593. else:
  594. msg = (
  595. "Reverse for '%(view)s' not found. '%(view)s' is not "
  596. "a valid view function or pattern name." % {'view': lookup_view_s}
  597. )
  598. raise NoReverseMatch(msg)