Do not use capturing groups when unnecessary in URLs
Review Request #10273 — Created Oct. 24, 2018 and submitted
Given a URL pattern of the form
((?P<capture>[a-z]+)/)?
, a call to
reverse with the kwargs{'capture': 'foo'}
will result in a
NoReverseMatch
exception. This occurs because thecapture
param gets
hidden behind a positional parameter and Django will expect the
positional parameter intead of the named parameter for the call to
reverse. We now no longer use capturing groups -- we explicltly mark the
outer group as non-capturing (e.g.(?:(?P<capture>[a-z]+)/)?
, which
works as expected.We previously were also using capturing groups in the form of
?(P<capture>(a|b))
. Not only will a non-capturing group work here, the
group isn't needed at all: a expression of the form(?P<capture>a|b)
is sufficient. All instances of this have been fixed.
- Ran unit tests.
- Viewed the diff fragment view for an interdiff.
- Viewed the e-mail preview views in html and text formats.
Description | From | Last Updated |
---|---|---|
Typo in the description: "paramter" -> "parameter" |
chipx86 |
- Description:
-
Given a URL pattern of the form
((?P<capture>[a-z]+)/)?
, a call toreverse with the kwargs {'capture': 'foo'}
will result in aNoReverseMatch
exception. This occurs because thecapture
param gets~ hidden behind a positional paramter and Django will expect the ~ hidden behind a positional parameter and Django will expect the positional parameter intead of the named parameter for the call to reverse. We now no longer use capturing groups -- we explicltly mark the outer group as non-capturing (e.g. (?:(?P<capture>[a-z]+)/)?
, whichworks as expected. We previously were also using capturing groups in the form of
?(P<capture>(a|b))
. Not only will a non-capturing group work here, thegroup isn't needed at all: a expression of the form (?P<capture>a|b)
is sufficient. All instances of this have been fixed.