Django provides the url tag to help you add links to your web pages. If possible, it is best to avoid hard-coded links. If you modify the URLconf file and thus change the URL pattern, you might wind up needing to change every place in your code that you hard-coded the link.
To solve this problem, the url tag allows you to specify the view function, including arguments, directly. The url tag results in an absolute URL being placed in the rendered HTML document.
The first argument inside the url tag is a path to a view function, such as the path to the details() function in the views.py file of the People application in the iFriends project:
iFriends.People.views.details
Additional arguments are optional and should be separated by commas with no spaces. Arguments are considered positional unless you specify a keyword=value. For example:
{url mySite.arch.views.list arg1,arg2,year=2008 %}
By the Way
If you are using named URL patterns, you can refer to the name of the pattern in the url tag instead of using the path to the view.
The arguments specified in the url tag must correspond to what is defined in the URLconf file. If they do not, no URL is returned.
Watch Out!
The url tag searches for the first match in the URLconf file. If multiple patterns are pointing to the same view, either use named patterns, or make certain that the first one in the list is the one you want.
Try It Yourself: Add Dynamic Links to a TemplateIn this section, you will modify the person_index.html file you created earlier in this hour to add dynamic links to the details page for each person in the list. Follow these steps to add dynamic links that refer to the view function directly to the index view of the People application:
Listing 8.4. Full Contents of iFriends/templates/People/person_index.html
|