Matching paths and reversing names
How does URLResolver walk nested includes in order, and how does reverse invert regex patterns back into concrete URL strings?
Forward URL matching and backward URL generation look like mirror images of one another, yet Django implements them with two completely different data structures. Forward resolution walks the live URLResolver tree depth-first until a pattern matches; backward reversal builds a pre-inverted lookup table once in URLResolver and then re-validates every generated string against the forward regex before returning it.
ch04-routing. Notice that reverse() never trusts string formatting alone: it runs the forward regular expression back over the candidate URL before quoting and returning it.Depth-first resolve() and ResolverMatch
When BaseHandler calls URLResolver, Django first runs RegexPattern on the root resolver (RegexPattern(r"^/), stripping the leading "/" and producing new_path. It then loops sequentially through URLResolver:
- If the child is a leaf
URLPattern, it testsURLPatternagainst.pattern new_path. On a hit, it merges captured kwargs with anydefault_argspassed topath()and returns aResolverMatchcarryingfunc,args,kwargs,url_name,app_names,namespaces,route,captured_kwargs,extra_kwargs, andtried. - If the child is a nested
URLResolver(aninclude()), it recurses. On a miss, the child raisesResolver404carrying every pattern it attempted; the parent merges those paths intotriedviaURLResolverso the debug._extend_tried 404page can print the complete tree of tried routes. - Look closely at lines 688–693 of
django/: if any named capture group matched, Django discards all unnamed positional groups (urls/ resolvers .py if not sub_match_dict: sub_match_args = args + sub_match). Mixing named and unnamed groups in one.args re_pathsilently drops the unnamed captures.
Because ResolverMatch implements __getitem__ over (self, BaseHandler can unpack callback, callback_args, callback_kwargs = self while simultaneously exposing resolver_match on HttpRequest. And because ResolverMatch explicitly raises pickle, a request carrying resolver_match can never be pickled accidentally into a cache or session.
Inverting regexes in _populate() and reverse()
Calling reverse triggers URLResolver the first time a language’s lookup table is needed. Inside a thread-local recursion guard on URLResolver ("populating"), _populate() walks reversed(self and builds three per-language dictionaries:
reverse_dict(aMultiValueDictkeyed by bothURLPattern.nameandURLPattern): for each leaf, Django feeds the compiled regex pattern string through.callback django, a lightweight regex parser that expands alternations and named groups into a list of.utils .regex_helper .normalize (format_string, param_names)pairs — turning"^stories/into(?P<slug>[-a-zA-Z0-9_]+)/ \\Z" [("stories/.%(slug)s/ ", ["slug"])] namespace_dict: maps each instance namespace name ("metro","sports","admin") to(prefix_pattern, sub_resolver).app_dict: maps each application namespace ("section","admin") to the list of instance namespaces mounted for that app.
Then URLResolver walks the candidate tuples for the requested view name or callable:
- Rejects mixed positional and keyword arguments (
ValueError). - Checks that the supplied
argscount orkwargskeys matchparams(accounting for anydefault_args). - Converts every value to text via the converter’s
StringConverter(.to_url StringConverter, treating.to_url ValueErroras a non-match so overloaded patterns with the same name can fall through cleanly). - Substitutes into the decoded
format_stringand re-runsreagainst the decoded string! That re-validation is why.search("^%s%s" % (re .escape(_prefix), pattern), candidate) reverse("story-detail", kwargs={"slug": "bad/raisesslug"}) NoReverseMatchinstead of emitting a broken link containing a slash. - Percent-encodes the validated path with
urllib(keeping RFC 3986 sub-delims) and passes it through.parse .quote escape_leading_slashesso a reversed path can never start with"//"and turn into a scheme-relative open redirect.
Recording resolve, reverse, and namespaces live
Watch all four mechanics — normalize, resolve, reverse validation, and URL namespaces — run on Django 6.1.3:
normalize('^stories/(?P<slug>[-a-zA-Z0-9_]+)/\\Z') -> [('stories/%(slug)s/', ['slug'])]
resolve('/stories/bridge-bond-passes/') -> view_name='story-detail' route='stories/<slug:slug>/' kwargs={'slug': 'bridge-bond-passes'} tried_patterns=4
reverse('story-detail', kwargs={'slug': 'bridge-bond-passes'}) -> '/stories/bridge-bond-passes/'
reverse('story-detail', slug='bad/slug') -> NoReverseMatch: Reverse for 'story-detail' with keyword arguments '{'slug': 'bad/slug'}' not found. 1 pattern(s) tried: ['stories/(?P<slug>[-a-zA-Z0-9_]+)/\\Z']
namespaces (app_name='section'): reverse('section:front')='/sports/' reverse('metro:front')='/metro/' reverse('section:front', current_app='sports')='/sports/'
resolve('/sports/') -> app_name='section' namespace='sports' view_name='sports:front'
STOP AND LOOK AT LINE 5 OF THAT TRACE!
We mounted the same reusable app (app_name = "section") under two instance URL namespaces in order: "metro/" first (namespace="metro"), then "sports/" second (namespace="sports"). When we called reverse("section: without specifying "current_app", Django returned "/sports/" — the second mount, not the first!
Why? Look back at line 558 of django/ and lines 64–73 of django/:
URLResolverwalks._populate reversed(self, so it visits.url_patterns) "sports/"before"metro/"and buildsapp_dict["section"] = ["sports", "metro"].- When
reverse("section:sees thatfront") "section"is an application namespace not shared by any instance namespace name, and no"current_app"was passed, line 73 picksapp_list[0]— which is"sports", the last declaration in"urls.py"! - Pass
current_app="metro"(or reverse directly by instance namespace"metro:front"), and Django picks"metro"deterministically.
Linear resolve() vs. constant-time reverse()
Compare the measured scaling of forward resolution and backward reversal across 10, 50, 200, and 500 routes (2,000 calls × 5 trials):
URL resolution O(N) scaling matching last route (2,000 calls x 5 trials, microseconds)
routes static_path_us slug_path_us re_path_us slug/static warm_reverse_us populate_ms
10 6.05 13.34 13.57 2.2x 5.58 0.11
50 13.15 44.11 47.15 3.4x 5.59 0.48
200 40.36 164.08 177.32 4.1x 5.64 1.90
500 93.52 402.60 432.19 4.3x 5.70 4.78
Every 50x jump in route count increases resolve() cost almost linearly — 6.05 -> 93.52 us for static path(), 13 for parameterized path(), 13 for re_path() — while warm reverse() stays glued to 5.6 us across all four sizes because reverse_dict is a hash table built once during _populate() (0.11 -> 4.78 ms).
Where resolving and reversing leak
- Calling
reverse()at module import time crashes or deadlocks. Importing a model or view that callsreverse()at class-definition time (for example,success_url = reverse("edition-front")) triggersURLResolverwhile._populate "urls.py"is still half-imported — causing circular-importImproperlyConfigurederrors! Usereverse_lazy, which wrapsreverseinsidedjangoso evaluation waits until runtime..utils .functional .lazy - Duplicate names and double-mounted apps pick the LAST declaration. Because
_populate()iteratesreversed(self, both duplicate URL names and un-qualified.url_patterns) app_namereversals prefer the last entry in"urls.py", while forwardresolve()prefers the first! - Named regexes with lookarounds or backreferences can break
normalize().djangohandles standard groups and alternations; exotic regex syntax in.utils .regex_helper .normalize re_pathmay fail to reverse cleanly even when forwardresolve()matches.
Once resolve() hands back a ResolverMatch, Django calls the view callback — which is rarely a raw function once decorators get involved. Let’s unwrap view decorators next in Function views and decorator wrappers.