One of Django's best features is its ability to allow developers to define an elegant URL scheme. Having a good URL scheme will make your code much cleaner and simpler to administer. It will also be easier for web users to access applications on the website in a clean, professional way.
URL processing is done by Django's URL dispatcher. At first glance, Django's URL dispatcher algorithm may seem complex and difficult. However, after you get used to it, you will be able to quickly implement and change URL behavior with only a few keystrokes.
When Django receives an HTTP request, it looks at the ROOT_URLCONF setting in the settings.py file and finds the name of the URLconf file. It then opens the URLconf file and finds the urlpatterns variable. The urlpatterns variable is a list of user-defined URL patterns that correspond to view functions. Django scans the list of URL patterns until it finds one that matches the request. It then calls the view function, passing in the request object as the first argument.
Each URL pattern entry is also a Python list. The first element of each list is the pattern that Django tries to match to the HTTP request. The second element is the view function that should be called.
The simplest way to illustrate this is with some examples. Consider the iFriends website. We defined a view called index that should be called if the URL /People is accessed. The resulting entry in the patterns variable of the URLconf file is as follows:
r'^People/$', 'iFriends.People.views.index'),
Using this URL pattern, when a web browser sends an HTTP request to access the URL /People, the index function in the iFriends/People/views.py file is called.
Try It Yourself: Add a New URL Pattern to the URLconf FileThe index view was configured in Hour 2. In this section, you will prepare another view named details() that will eventually display detailed information about a specific person. Follow these steps to create the details() view and then add a pattern to handle the view in the URLconf file:
Watch Out! The Django URL dispatcher is case-sensitive. Make certain that the case matches between the patterns in the URLconf file and the views.py file. Listing 4.1 shows the complete urls.py file. Listing 4.1. Full Contents of the iFriends\urls.py File with the New details() Entry
Listing 4.2 shows the complete views.py file. Listing 4.2. Full Contents of the iFriends\People\views.py File Including the details() view
|