As you add more applications to your website, your URLconf file can become congested with all the URL patterns for the different applications. The best way to avoid this is to create an URLconf file for each application.
Django provides the include() function to add URLconf files to the URLconf file. The include() function accepts the location of the URLconf file using . (dot) syntax and takes the place of the view function in the URL pattern. For example, to include a new URLconf file, iFriends/Blog/urls.py, to be used when the /Blog/ URL is accessed, you would specify the following URL pattern:
(r'^Blog/', include('iFriends.Blog.urls')),
By the Way
Notice that the r'^Blog/' pattern doesn't include the $ character. This is because the URL dispatcher deletes the portion of the URL that is read before executing the include and passes only the remaining string. For example, if the preceding URL were Blog/index, only index would be passed in as the URL to the new URLconf file. The new URLconf file needs to have the trailing $ character specified in the pattern.
Django passes captured parameters through the include() function to other URLconf files. For example, if your root URLconf file contained the following pattern:
(r'^(?P<pID>\d+)/Blog/', include('iFriends.Blog.urls')),
the pID argument would still be captured and passed to the display() view function in the following pattern in the iFriends/Blog/urls.py URLconf file:
(r'^', 'iFriends.Blog.views.display'),
Django also allows you to pass a dictionary of extra options as an argument after the include() function. This passes the extra options to other URLconf files, which pass them to the view functions they invoke. For example, if your root URLconf file contains the following pattern:
(r'^Blog/', include('iFriends.Blog.urls'), {'pID':0}),
the dictionary containing the pID argument is still passed to the display() view function in the following pattern in the iFriends/Blog/urls.py URLconf file:
(r'^', 'iFriends.Blog.views.display'),
Try It Yourself: Add an URLconf File to Your Django ProjectIn this section, you will add a new URLconf file to the People application of the iFriends project. Follow these steps to create the new URLconf file and modify the root URLconf file to include the new one:
Listing 6.4. Full Contents of the iFriends\People\urls.py File
Listing 6.5. Full Contents of the iFriends\urls.py File
|