Simpler URLconfs
In case you missed it in yesterday's "week in review" entry, we've made an improvement to the URLconf-parsing system so that you can specify URLs using non-named groups as an alternative to named groups.
For example, here's how the old (but still supported) syntax looked:
urlpatterns = patterns('',
(r'^articles/2003/$', 'news.views.special_case_2003'),
(r'^articles/(?P<year>\d{4})/$', 'news.views.year_archive'),
(r'^articles/(?P<year>\d{4})/(?P<month>\d\d)/$', 'news.views.month_archive'),
(r'^articles/(?P<year>\d{4})/(?P<month>\d\d)/(?P<day>\d\d)/$', 'news.views.article_detail'),
)
And here's the equivalent using the new non-named group syntax:
urlpatterns = patterns('',
(r'^articles/2003/$', 'news.views.special_case_2003'),
(r'^articles/(\d{4})/$', 'news.views.year_archive'),
(r'^articles/(\d{4})/(\d\d)/$', 'news.views.month_archive'),
(r'^articles/(\d{4})/(\d\d)/(\d\d)/$', 'news.views.article_detail'),
)
To capture something, just put parenthesis around it. Of course, you can still use named groups.
If your URLconf uses non-named groups (with simple parenthesis, as in the second example), the captured values will be passed to your view as positional arguments -- so you'll need to make sure the arguments to your view function are in the same order as they appear in the URL. If your URLconf uses named groups (as in the first example), the captured values will be passed as keyword arguments -- so the order doesn't matter.
Thanks to Aaron Swartz for originally suggesting this improvement!
Posted by Adrian Holovaty on November 28, 2005
Comments
Adrian Holovaty November 29, 2005 at 8:44 a.m.
Hugo -- the old syntax is still supported for explicitness-lovers like you and me. :)
Daniel James November 30, 2005 at 4:46 a.m.
I kind of like explicit parameters as well, but find the old syntax tricky. How about something like:
urlpatterns = patterns('',
(r'^articles/2003/$', 'news.views.special_case_2003'),
(r'^articles/(\d{4})/$', 'news.views.year_archive', 'year'),
(r'^articles/(\d{4})/(\d\d)/$', 'news.views.month_archive', 'year', 'month'),
(r'^articles/(\d{4})/(\d\d)/(\d\d)/$', 'news.views.article_detail', 'year', 'month', 'day'),
)
Just an idle thought though...
nirvdrum November 30, 2005 at 9:52 a.m.
I have to agree with Hugo. Here, the time saved in typing is easily trumped by the time required to look up the view code to see what the parameters are. I'm all for giving people features that save time, but this one seems to minimize clarity more than it does time.
Comments are closed
To prevent spam, comments are no longer allowed after sixty days.


hugo November 29, 2005 at 1:31 a.m.
Actually, seeing them side-by-side, I know what I dislike (beside the fact that positionals are - well - bound to their position): with the old syntax I can see immediately what parts construct a URI and what goes into it. With the "shortened" syntax I need to go into the view itself to see what parameters it needs to see what parts are.