Version 5 (modified by Slowness Chen, 17 years ago) (diff)

add title

CookBook - Write a DRY URL configuration


In a url configuration file, we use the first argument to the patterns() function to specify a prefix to apply to each view function , avoiding typing that out for each entry in urlpatterns. but in the practical application, it is quite normal that only part of patterns have the common prefix. In that case, we cann't use a prefix directly for example:

urlpatterns = patterns( ''
             (r'^/?$', 'django.views.generic.date_based.archive_index'),
             (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$', 'django.views.generic.date_based.archive_month'),
             (r'^tag/(?P<tag>\w+)/$', 'weblog.views.tag'),


All Django URL resolver needs is a urlpatterns variable in the url configuration, which is a list of pattern objects returned by the patterns() function. So we can do as the following to make our configuration DRY:

urlpatterns = patterns( 'django.views.generic.date_based'
             (r'^/?$', 'archive_index'),

urlpatterns += patterns('weblog.views',
             (r'^tag/(?P<tag>\w+)/$', 'tag'),   
Back to Top