Weblog

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.

Read the full documentation.

Thanks to Aaron Swartz for originally suggesting this improvement!

Posted by Adrian Holovaty on November 28, 2005