PageRenderTime 31ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/django/urls/resolvers.py

http://github.com/django/django
Python | 685 lines | 613 code | 35 blank | 37 comment | 44 complexity | e8287cf9e32d307849854483bd8efeda MD5 | raw file
Possible License(s): BSD-3-Clause, MIT
  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 _lazy_re_compile, 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. ) from e
  164. def __str__(self):
  165. return str(self._regex)
  166. _PATH_PARAMETER_COMPONENT_RE = _lazy_re_compile(
  167. r'<(?:(?P<converter>[^>:]+):)?(?P<parameter>[^>]+)>'
  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['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['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 %r uses invalid converter %r.'
  203. % (original_route, raw_converter)
  204. ) from e
  205. converters[parameter] = converter
  206. parts.append('(?P<' + parameter + '>' + converter.regex + ')')
  207. if is_endpoint:
  208. parts.append('$')
  209. return ''.join(parts), converters
  210. class RoutePattern(CheckURLMixin):
  211. regex = LocaleRegexDescriptor('_route')
  212. def __init__(self, route, name=None, is_endpoint=False):
  213. self._route = route
  214. self._regex_dict = {}
  215. self._is_endpoint = is_endpoint
  216. self.name = name
  217. self.converters = _route_to_regex(str(route), is_endpoint)[1]
  218. def match(self, path):
  219. match = self.regex.search(path)
  220. if match:
  221. # RoutePattern doesn't allow non-named groups so args are ignored.
  222. kwargs = match.groupdict()
  223. for key, value in kwargs.items():
  224. converter = self.converters[key]
  225. try:
  226. kwargs[key] = converter.to_python(value)
  227. except ValueError:
  228. return None
  229. return path[match.end():], (), kwargs
  230. return None
  231. def check(self):
  232. warnings = self._check_pattern_startswith_slash()
  233. route = self._route
  234. if '(?P<' in route or route.startswith('^') or route.endswith('$'):
  235. warnings.append(Warning(
  236. "Your URL pattern {} has a route that contains '(?P<', begins "
  237. "with a '^', or ends with a '$'. This was likely an oversight "
  238. "when migrating to django.urls.path().".format(self.describe()),
  239. id='2_0.W001',
  240. ))
  241. return warnings
  242. def _compile(self, route):
  243. return re.compile(_route_to_regex(route, self._is_endpoint)[0])
  244. def __str__(self):
  245. return str(self._route)
  246. class LocalePrefixPattern:
  247. def __init__(self, prefix_default_language=True):
  248. self.prefix_default_language = prefix_default_language
  249. self.converters = {}
  250. @property
  251. def regex(self):
  252. # This is only used by reverse() and cached in _reverse_dict.
  253. return re.compile(self.language_prefix)
  254. @property
  255. def language_prefix(self):
  256. language_code = get_language() or settings.LANGUAGE_CODE
  257. if language_code == settings.LANGUAGE_CODE and not self.prefix_default_language:
  258. return ''
  259. else:
  260. return '%s/' % language_code
  261. def match(self, path):
  262. language_prefix = self.language_prefix
  263. if path.startswith(language_prefix):
  264. return path[len(language_prefix):], (), {}
  265. return None
  266. def check(self):
  267. return []
  268. def describe(self):
  269. return "'{}'".format(self)
  270. def __str__(self):
  271. return self.language_prefix
  272. class URLPattern:
  273. def __init__(self, pattern, callback, default_args=None, name=None):
  274. self.pattern = pattern
  275. self.callback = callback # the view
  276. self.default_args = default_args or {}
  277. self.name = name
  278. def __repr__(self):
  279. return '<%s %s>' % (self.__class__.__name__, self.pattern.describe())
  280. def check(self):
  281. warnings = self._check_pattern_name()
  282. warnings.extend(self.pattern.check())
  283. return warnings
  284. def _check_pattern_name(self):
  285. """
  286. Check that the pattern name does not contain a colon.
  287. """
  288. if self.pattern.name is not None and ":" in self.pattern.name:
  289. warning = Warning(
  290. "Your URL pattern {} has a name including a ':'. Remove the colon, to "
  291. "avoid ambiguous namespace references.".format(self.pattern.describe()),
  292. id="urls.W003",
  293. )
  294. return [warning]
  295. else:
  296. return []
  297. def resolve(self, path):
  298. match = self.pattern.match(path)
  299. if match:
  300. new_path, args, kwargs = match
  301. # Pass any extra_kwargs as **kwargs.
  302. kwargs.update(self.default_args)
  303. return ResolverMatch(self.callback, args, kwargs, self.pattern.name, route=str(self.pattern))
  304. @cached_property
  305. def lookup_str(self):
  306. """
  307. A string that identifies the view (e.g. 'path.to.view_function' or
  308. 'path.to.ClassBasedView').
  309. """
  310. callback = self.callback
  311. if isinstance(callback, functools.partial):
  312. callback = callback.func
  313. if not hasattr(callback, '__name__'):
  314. return callback.__module__ + "." + callback.__class__.__name__
  315. return callback.__module__ + "." + callback.__qualname__
  316. class URLResolver:
  317. def __init__(self, pattern, urlconf_name, default_kwargs=None, app_name=None, namespace=None):
  318. self.pattern = pattern
  319. # urlconf_name is the dotted Python path to the module defining
  320. # urlpatterns. It may also be an object with an urlpatterns attribute
  321. # or urlpatterns itself.
  322. self.urlconf_name = urlconf_name
  323. self.callback = None
  324. self.default_kwargs = default_kwargs or {}
  325. self.namespace = namespace
  326. self.app_name = app_name
  327. self._reverse_dict = {}
  328. self._namespace_dict = {}
  329. self._app_dict = {}
  330. # set of dotted paths to all functions and classes that are used in
  331. # urlpatterns
  332. self._callback_strs = set()
  333. self._populated = False
  334. self._local = Local()
  335. def __repr__(self):
  336. if isinstance(self.urlconf_name, list) and self.urlconf_name:
  337. # Don't bother to output the whole list, it can be huge
  338. urlconf_repr = '<%s list>' % self.urlconf_name[0].__class__.__name__
  339. else:
  340. urlconf_repr = repr(self.urlconf_name)
  341. return '<%s %s (%s:%s) %s>' % (
  342. self.__class__.__name__, urlconf_repr, self.app_name,
  343. self.namespace, self.pattern.describe(),
  344. )
  345. def check(self):
  346. messages = []
  347. for pattern in self.url_patterns:
  348. messages.extend(check_resolver(pattern))
  349. messages.extend(self._check_custom_error_handlers())
  350. return messages or self.pattern.check()
  351. def _check_custom_error_handlers(self):
  352. messages = []
  353. # All handlers take (request, exception) arguments except handler500
  354. # which takes (request).
  355. for status_code, num_parameters in [(400, 2), (403, 2), (404, 2), (500, 1)]:
  356. try:
  357. handler, param_dict = self.resolve_error_handler(status_code)
  358. except (ImportError, ViewDoesNotExist) as e:
  359. path = getattr(self.urlconf_module, 'handler%s' % status_code)
  360. msg = (
  361. "The custom handler{status_code} view '{path}' could not be imported."
  362. ).format(status_code=status_code, path=path)
  363. messages.append(Error(msg, hint=str(e), id='urls.E008'))
  364. continue
  365. signature = inspect.signature(handler)
  366. args = [None] * num_parameters
  367. try:
  368. signature.bind(*args)
  369. except TypeError:
  370. msg = (
  371. "The custom handler{status_code} view '{path}' does not "
  372. "take the correct number of arguments ({args})."
  373. ).format(
  374. status_code=status_code,
  375. path=handler.__module__ + '.' + handler.__qualname__,
  376. args='request, exception' if num_parameters == 2 else 'request',
  377. )
  378. messages.append(Error(msg, id='urls.E007'))
  379. return messages
  380. def _populate(self):
  381. # Short-circuit if called recursively in this thread to prevent
  382. # infinite recursion. Concurrent threads may call this at the same
  383. # time and will need to continue, so set 'populating' on a
  384. # thread-local variable.
  385. if getattr(self._local, 'populating', False):
  386. return
  387. try:
  388. self._local.populating = True
  389. lookups = MultiValueDict()
  390. namespaces = {}
  391. apps = {}
  392. language_code = get_language()
  393. for url_pattern in reversed(self.url_patterns):
  394. p_pattern = url_pattern.pattern.regex.pattern
  395. if p_pattern.startswith('^'):
  396. p_pattern = p_pattern[1:]
  397. if isinstance(url_pattern, URLPattern):
  398. self._callback_strs.add(url_pattern.lookup_str)
  399. bits = normalize(url_pattern.pattern.regex.pattern)
  400. lookups.appendlist(
  401. url_pattern.callback,
  402. (bits, p_pattern, url_pattern.default_args, url_pattern.pattern.converters)
  403. )
  404. if url_pattern.name is not None:
  405. lookups.appendlist(
  406. url_pattern.name,
  407. (bits, p_pattern, url_pattern.default_args, url_pattern.pattern.converters)
  408. )
  409. else: # url_pattern is a URLResolver.
  410. url_pattern._populate()
  411. if url_pattern.app_name:
  412. apps.setdefault(url_pattern.app_name, []).append(url_pattern.namespace)
  413. namespaces[url_pattern.namespace] = (p_pattern, url_pattern)
  414. else:
  415. for name in url_pattern.reverse_dict:
  416. for matches, pat, defaults, converters in url_pattern.reverse_dict.getlist(name):
  417. new_matches = normalize(p_pattern + pat)
  418. lookups.appendlist(
  419. name,
  420. (
  421. new_matches,
  422. p_pattern + pat,
  423. {**defaults, **url_pattern.default_kwargs},
  424. {**self.pattern.converters, **url_pattern.pattern.converters, **converters}
  425. )
  426. )
  427. for namespace, (prefix, sub_pattern) in url_pattern.namespace_dict.items():
  428. current_converters = url_pattern.pattern.converters
  429. sub_pattern.pattern.converters.update(current_converters)
  430. namespaces[namespace] = (p_pattern + prefix, sub_pattern)
  431. for app_name, namespace_list in url_pattern.app_dict.items():
  432. apps.setdefault(app_name, []).extend(namespace_list)
  433. self._callback_strs.update(url_pattern._callback_strs)
  434. self._namespace_dict[language_code] = namespaces
  435. self._app_dict[language_code] = apps
  436. self._reverse_dict[language_code] = lookups
  437. self._populated = True
  438. finally:
  439. self._local.populating = False
  440. @property
  441. def reverse_dict(self):
  442. language_code = get_language()
  443. if language_code not in self._reverse_dict:
  444. self._populate()
  445. return self._reverse_dict[language_code]
  446. @property
  447. def namespace_dict(self):
  448. language_code = get_language()
  449. if language_code not in self._namespace_dict:
  450. self._populate()
  451. return self._namespace_dict[language_code]
  452. @property
  453. def app_dict(self):
  454. language_code = get_language()
  455. if language_code not in self._app_dict:
  456. self._populate()
  457. return self._app_dict[language_code]
  458. @staticmethod
  459. def _join_route(route1, route2):
  460. """Join two routes, without the starting ^ in the second route."""
  461. if not route1:
  462. return route2
  463. if route2.startswith('^'):
  464. route2 = route2[1:]
  465. return route1 + route2
  466. def _is_callback(self, name):
  467. if not self._populated:
  468. self._populate()
  469. return name in self._callback_strs
  470. def resolve(self, path):
  471. path = str(path) # path may be a reverse_lazy object
  472. tried = []
  473. match = self.pattern.match(path)
  474. if match:
  475. new_path, args, kwargs = match
  476. for pattern in self.url_patterns:
  477. try:
  478. sub_match = pattern.resolve(new_path)
  479. except Resolver404 as e:
  480. sub_tried = e.args[0].get('tried')
  481. if sub_tried is not None:
  482. tried.extend([pattern] + t for t in sub_tried)
  483. else:
  484. tried.append([pattern])
  485. else:
  486. if sub_match:
  487. # Merge captured arguments in match with submatch
  488. sub_match_dict = {**kwargs, **self.default_kwargs}
  489. # Update the sub_match_dict with the kwargs from the sub_match.
  490. sub_match_dict.update(sub_match.kwargs)
  491. # If there are *any* named groups, ignore all non-named groups.
  492. # Otherwise, pass all non-named arguments as positional arguments.
  493. sub_match_args = sub_match.args
  494. if not sub_match_dict:
  495. sub_match_args = args + sub_match.args
  496. current_route = '' if isinstance(pattern, URLPattern) else str(pattern.pattern)
  497. return ResolverMatch(
  498. sub_match.func,
  499. sub_match_args,
  500. sub_match_dict,
  501. sub_match.url_name,
  502. [self.app_name] + sub_match.app_names,
  503. [self.namespace] + sub_match.namespaces,
  504. self._join_route(current_route, sub_match.route),
  505. )
  506. tried.append([pattern])
  507. raise Resolver404({'tried': tried, 'path': new_path})
  508. raise Resolver404({'path': path})
  509. @cached_property
  510. def urlconf_module(self):
  511. if isinstance(self.urlconf_name, str):
  512. return import_module(self.urlconf_name)
  513. else:
  514. return self.urlconf_name
  515. @cached_property
  516. def url_patterns(self):
  517. # urlconf_module might be a valid set of patterns, so we default to it
  518. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  519. try:
  520. iter(patterns)
  521. except TypeError as e:
  522. msg = (
  523. "The included URLconf '{name}' does not appear to have any "
  524. "patterns in it. If you see valid patterns in the file then "
  525. "the issue is probably caused by a circular import."
  526. )
  527. raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e
  528. return patterns
  529. def resolve_error_handler(self, view_type):
  530. callback = getattr(self.urlconf_module, 'handler%s' % view_type, None)
  531. if not callback:
  532. # No handler specified in file; use lazy import, since
  533. # django.conf.urls imports this file.
  534. from django.conf import urls
  535. callback = getattr(urls, 'handler%s' % view_type)
  536. return get_callable(callback), {}
  537. def reverse(self, lookup_view, *args, **kwargs):
  538. return self._reverse_with_prefix(lookup_view, '', *args, **kwargs)
  539. def _reverse_with_prefix(self, lookup_view, _prefix, *args, **kwargs):
  540. if args and kwargs:
  541. raise ValueError("Don't mix *args and **kwargs in call to reverse()!")
  542. if not self._populated:
  543. self._populate()
  544. possibilities = self.reverse_dict.getlist(lookup_view)
  545. for possibility, pattern, defaults, converters in possibilities:
  546. for result, params in possibility:
  547. if args:
  548. if len(args) != len(params):
  549. continue
  550. candidate_subs = dict(zip(params, args))
  551. else:
  552. if set(kwargs).symmetric_difference(params).difference(defaults):
  553. continue
  554. if any(kwargs.get(k, v) != v for k, v in defaults.items()):
  555. continue
  556. candidate_subs = kwargs
  557. # Convert the candidate subs to text using Converter.to_url().
  558. text_candidate_subs = {}
  559. match = True
  560. for k, v in candidate_subs.items():
  561. if k in converters:
  562. try:
  563. text_candidate_subs[k] = converters[k].to_url(v)
  564. except ValueError:
  565. match = False
  566. break
  567. else:
  568. text_candidate_subs[k] = str(v)
  569. if not match:
  570. continue
  571. # WSGI provides decoded URLs, without %xx escapes, and the URL
  572. # resolver operates on such URLs. First substitute arguments
  573. # without quoting to build a decoded URL and look for a match.
  574. # Then, if we have a match, redo the substitution with quoted
  575. # arguments in order to return a properly encoded URL.
  576. candidate_pat = _prefix.replace('%', '%%') + result
  577. if re.search('^%s%s' % (re.escape(_prefix), pattern), candidate_pat % text_candidate_subs):
  578. # safe characters from `pchar` definition of RFC 3986
  579. url = quote(candidate_pat % text_candidate_subs, safe=RFC3986_SUBDELIMS + '/~:@')
  580. # Don't allow construction of scheme relative urls.
  581. return escape_leading_slashes(url)
  582. # lookup_view can be URL name or callable, but callables are not
  583. # friendly in error messages.
  584. m = getattr(lookup_view, '__module__', None)
  585. n = getattr(lookup_view, '__name__', None)
  586. if m is not None and n is not None:
  587. lookup_view_s = "%s.%s" % (m, n)
  588. else:
  589. lookup_view_s = lookup_view
  590. patterns = [pattern for (_, pattern, _, _) in possibilities]
  591. if patterns:
  592. if args:
  593. arg_msg = "arguments '%s'" % (args,)
  594. elif kwargs:
  595. arg_msg = "keyword arguments '%s'" % kwargs
  596. else:
  597. arg_msg = "no arguments"
  598. msg = (
  599. "Reverse for '%s' with %s not found. %d pattern(s) tried: %s" %
  600. (lookup_view_s, arg_msg, len(patterns), patterns)
  601. )
  602. else:
  603. msg = (
  604. "Reverse for '%(view)s' not found. '%(view)s' is not "
  605. "a valid view function or pattern name." % {'view': lookup_view_s}
  606. )
  607. raise NoReverseMatch(msg)