Django 6.1.3

4.4 HTTP, routing, and views

Matching paths and reversing names

How does URLResolver.resolve 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._populate and then re-validates every generated string against the forward regex before returning it.

Figure 4.2 Every compiled regex, normalized template, and result is parsed from 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.resolve_request calls URLResolver.resolve, Django first runs RegexPattern.match on the root resolver (RegexPattern(r"^/")), stripping the leading "/" and producing new_path. It then loops sequentially through URLResolver.url_patterns:

Because ResolverMatch implements __getitem__ over (self.func, self.args, self.kwargs), BaseHandler._get_response can unpack callback, callback_args, callback_kwargs = self.resolve_request(request) while simultaneously exposing resolver_match on HttpRequest. And because ResolverMatch.__reduce_ex__ explicitly raises pickle.PicklingError, 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._populate the first time a language’s lookup table is needed. Inside a thread-local recursion guard on URLResolver._local ("populating"), _populate() walks reversed(self.url_patterns) and builds three per-language dictionaries:

  1. reverse_dict (a MultiValueDict keyed by both URLPattern.name and URLPattern.callback): for each leaf, Django feeds the compiled regex pattern string through django.utils.regex_helper.normalize, a lightweight regex parser that expands alternations and named groups into a list of (format_string, param_names) pairs — turning "^stories/(?P<slug>[-a-zA-Z0-9_]+)/\\Z" into [("stories/%(slug)s/", ["slug"])].
  2. namespace_dict: maps each instance namespace name ("metro", "sports", "admin") to (prefix_pattern, sub_resolver).
  3. app_dict: maps each application namespace ("section", "admin") to the list of instance namespaces mounted for that app.

Then URLResolver._reverse_with_prefix walks the candidate tuples for the requested view name or callable:

  1. Rejects mixed positional and keyword arguments (ValueError).
  2. Checks that the supplied args count or kwargs keys match params (accounting for any default_args).
  3. Converts every value to text via the converter’s StringConverter.to_url (StringConverter.to_url, treating ValueError as a non-match so overloaded patterns with the same name can fall through cleanly).
  4. Substitutes into the decoded format_string and re-runs re.search("^%s%s" % (re.escape(_prefix), pattern), candidate) against the decoded string! That re-validation is why reverse("story-detail", kwargs={"slug": "bad/slug"}) raises NoReverseMatch instead of emitting a broken link containing a slash.
  5. Percent-encodes the validated path with urllib.parse.quote (keeping RFC 3986 sub-delims) and passes it through escape_leading_slashes so 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:

Recorded on Django 6.1.3 ch04-routing script
  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:front") without specifying "current_app", Django returned "/sports/" — the second mount, not the first!

Why? Look back at line 558 of django/urls/resolvers.py and lines 64–73 of django/urls/base.py:

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):

Recorded on Django 6.1.3 ch04-bench script
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.34 -> 402.60 us for parameterized path(), 13.57 -> 432.19 us 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

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.