This article mainly introduces the collaborative working methods of URLconf and include () in Django. Django is one of the most famous Python public-profile frameworks. For more information, see
How the captured parameters work with include ()
An contained URLconf receives any captured parameters from parent URLconfs, such:
# root urls.pyfrom django.conf.urls.defaults import *urlpatterns = patterns('', (r'^(?P
\w+)/blog/', include('foo.urls.blog')),)# foo/urls/blog.pyfrom django.conf.urls.defaults import *urlpatterns = patterns('', (r'^$', 'foo.views.blog_index'), (r'^archive/$', 'foo.views.blog_archive'),)
In this example, the captured username variable is passed to the contained URLconf and then to each view function in the URLconf.
Note that this captured parameter is always passed to each row in the contained URLconf, regardless of whether the view corresponding to those rows requires these parameters. Therefore, this technology is useful only when you really need the parameter to be passed.
How can the extra URLconf work with include ()?
Similarly, you can pass the extra URLconf option to include (), just as you can pass the extra URLconf option to the normal view through the dictionary. When you do this, each line containing the URLconf will receive those additional parameters.
For example, the following two URLconf files are functionally equivalent.
First:
# urls.pyfrom django.conf.urls.defaults import *urlpatterns = patterns('', (r'^blog/', include('inner'), {'blogid': 3}),)# inner.pyfrom django.conf.urls.defaults import *urlpatterns = patterns('', (r'^archive/$', 'mysite.views.archive'), (r'^about/$', 'mysite.views.about'), (r'^rss/$', 'mysite.views.rss'),)
Second
# urls.pyfrom django.conf.urls.defaults import *urlpatterns = patterns('', (r'^blog/', include('inner')),)# inner.pyfrom django.conf.urls.defaults import *urlpatterns = patterns('', (r'^archive/$', 'mysite.views.archive', {'blogid': 3}), (r'^about/$', 'mysite.views.about', {'blogid': 3}), (r'^rss/$', 'mysite.views.rss', {'blogid': 3}),)
This example is the same as the previous section on captured parameters (this is explained in the previous section). Additional options will always be passed to each row in the contained URLconf, no matter whether the view corresponding to the row actually receives these options as valid parameters, this technology is useful only when you really need the extra parameters to be passed. For this reason, this technology works only when you are sure to accept each URLconf of the additional options you provide.