resolvers.py 27 KB

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