Version 1 (modified by Slowness Chen, 18 years ago) ( diff )

create

Question:

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'),

)

Answer

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'), (r'(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),

)

urlpatterns += patterns('weblog.views',

(r'tag/(?P<tag>\w+)/$', 'tag'),

)

Note: See TracWiki for help on using the wiki.
Back to Top