Changes between Version 5 and Version 6 of CookBookMakeURLConfDRY


Ignore:
Timestamp:
May 2, 2006, 2:24:00 PM (19 years ago)
Author:
Adrian Holovaty
Comment:

Added note about rolling this into official URLconf docs

Legend:

Unmodified
Added
Removed
Modified
  • CookBookMakeURLConfDRY

    v5 v6  
    11= CookBook - Write a DRY URL configuration =
    22
    3 == Question: ==
    4 
    5 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:
    6 
    7 
    8 {{{
    9 urlpatterns = patterns( ''
    10              (r'^/?$', 'django.views.generic.date_based.archive_index'),
    11              (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$', 'django.views.generic.date_based.archive_month'),
    12              (r'^tag/(?P<tag>\w+)/$', 'weblog.views.tag'),
    13               )
    14 }}}
    15 
    16 
    17 == Answer: ==
    18 
    19 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:
    20 
    21 
    22 {{{
    23 urlpatterns = patterns( 'django.views.generic.date_based'
    24              (r'^/?$', 'archive_index'),
    25              (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),             
    26               )
    27 
    28 urlpatterns += patterns('weblog.views',
    29              (r'^tag/(?P<tag>\w+)/$', 'tag'),   
    30               )
    31 }}}
    32 
    33 
     3This page has been rolled into the official [http://www.djangoproject.com/documentation/url_dispatch/ URLconf docs].
Back to Top