| 1 | |
| 2 | == Question: == |
| 3 | |
| 4 | 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: |
| 5 | |
| 6 | urlpatterns = patterns( '' |
| 7 | (r'^/?$', 'django.views.generic.date_based.archive_index'), |
| 8 | (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$', 'django.views.generic.date_based.archive_month'), |
| 9 | (r'^tag/(?P<tag>\w+)/$', 'weblog.views.tag'), |
| 10 | ) |
| 11 | |
| 12 | == Answer == |
| 13 | |
| 14 | 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: |
| 15 | |
| 16 | urlpatterns = patterns( 'django.views.generic.date_based' |
| 17 | (r'^/?$', 'archive_index'), |
| 18 | (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'), |
| 19 | ) |
| 20 | |
| 21 | urlpatterns += patterns('weblog.views', |
| 22 | (r'^tag/(?P<tag>\w+)/$', 'tag'), |
| 23 | ) |
| 24 | |