Chapter 6. Configuring Web Page Views

<feature><title>What You’ll Learn in This Hour</title> <objective>

How to pass extra options to a view function

</objective>
<objective>

How to implement view prefixes

</objective>
<objective>

How to create URLconf files for each application

</objective>
<objective>

How to use a callable object instead of a string in an URL pattern

</objective>
</feature>

In Hour 4, “Creating the Initial Views,” you learned how to set up the initial views in the URLconf file. In this hour, we will expand on that topic to include more advanced configuration options for views. When designing your website, the more complete your URLconf file configuration for web page views is, the easier it is to keep your code in the view cohesive and clean.

The following sections describe some advanced configuration options that you can make in the URLconf and views.py files.

Passing Extra Options to a View

The syntax for URL patterns in the URLconf file allows you to add additional options that will be passed as additional arguments to the view function. This is different from capturing arguments inside the URL, which we have already discussed.

Django allows you to specify a Python dictionary containing arguments that will be passed to the view function by the URL dispatcher. For example, the following URL pattern passes a simple dictionary:

(r'^People/BlogArchive/$', 'iFriends.Blogs.views.index', {'label':'Archive'}),

When this URL pattern is accessed, the URL dispatcher calls the index() view function:

index(request, label='Archive')

By the Way

Just as with arguments captured from the URL, you need to add the arguments to the view function definition in the views.py file.

You can also capture arguments from the URL along with passing extra options in a dictionary. For example, the following URL pattern captures the year argument and passes a simple dictionary containing a label argument:

(r'^People/BlogArchive/(?P<year>d{4})/$', 'iFriends.Blogs.views.index',
{'label':'Archive'}),

When this URL pattern is accessed, the URL dispatcher calls the index() view function:

index(request, year='2008, label='Archive')

Watch Out!

It is possible to specify the same argument name in both the captured arguments and the extra options dictionary. If this occurs, the value in the extra options dictionary is used instead of the value that was captured from the URL.

The ability to pass options to view functions provides much more control over the views from the URLconf file. This gives you much more flexibility in the URL patterns that your website will handle. The captured arguments and the extra options dictionary also make the website easier to design and manage, because much of the control is contained in the URLconf file.

Using View Prefixes

In the preceding section, you added three new URL patterns to your URLconf file. In each pattern, you specified the same view, iFriends.People.views.details. This is a lot of redundant code. This also can be problematic if you change the project’s name, because you would need to change every URL pattern.

Django solves this problem by allowing you to specify a view prefix as the first argument to the patterns() function in the URLconf file. This can be used if all URL patterns being defined are located in the same view file. When a view prefix is added, you need to specify the view function in only the URL pattern. For example, if all URL patterns are located in the iFriends.Blogs.views file, you could use the following code to define the URL patterns for the index() and details() view functions:

urlpatterns = patterns('iFriends.Blogs.views',
    (r'^Blogs/$', 'index'),
    (r'^Blogs/Details/$', 'details'),
)

Sometimes you may need to have more than one prefix defined in the same URLconf file. You can use more than one prefix in the same URLconf file by calling the patterns() function multiple times and appending them to one another using the += operator, as shown in the following code snippet:

urlpatterns = patterns('iFriends.Blogs.views',
    (r'^Blogs/$', 'index'),
    (r'^Blogs/Details/$', 'details'),
)

urlpatterns += patterns('iFriends.People.views',
    (r'^People/$', 'index'),
    (r'^People/Details/$', 'details'),
)

Using Additional URLconf Files

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'),

Calling the View Functions Directly

Django supports an alternative method of calling the view functions from the URLconf file. Instead of pointing to the location of the view function using a .-based syntax string, you can import the function into the URLconf file and then use the function name instead. For example, if your current view file contains the following URL patterns that point to an index() and display() view functions:

(r'^Blog/List/$', 'iFriends.Blog.views.index'),
(r'^Blog/Display/$', 'iFriends.Blog.views.display'),

you could import the index() and display() view functions in the URLconf file using the following line of code:

from iFriends.Blog.views import index, display

and then you could pass callable function objects directly using the following code:

(r'^Blog/List/$', index),
(r'^Blog/Display/$', display),

Summary

In this hour, you learned how to create dictionaries of arguments and pass them to the view functions from the URLconf file. You also learned how to keep your URLconf files cleaner by using view prefixes and separating application URL patterns into their own URLconf files. We also covered how to specify the view function directly in the URL pattern.

Q&A

Q.

If I need to include only one extra variable, can I just specify the variable as a parameter after the view location in the URL pattern?

A.

The extra options must be contained in a dictionary. You can add the dictionary to the URL pattern as follows:

 (r'^Blogs/', 'mySite.Blogs.views.index', {'maxSize':10}),

Q.

Is there a way to get the absolute URL for a view in my Python code?

A.

Yes, Django provides the django.core.urlresolvers.reverse(viewname, urlconf=None, args=None, kwargs=None) function that will return the absolute URL for a view function. The reverse() function accepts either a function reference or a string version of the name as the viewname argument. The reverse() function also accepts optional arguments that allow you to specify which Urlconf file to use and the args and kwargs that should be passed to the view in the absolute URL. For example, consider the following URL:

 (r'^People/Details/(?P<pID>d+)/$', 'details'),

The following code allows you to retrieve the absolute URL for the iFriends.People.views.details view for a specific userID:

from django.core.urlresolvers import reverse
from iFriends.People.views import details
def getURL(userID):
    absoluteURL = reverse(details, args=[userID])

Workshop

The workshop consists of a set of questions and answers designed to solidify your understanding of the material covered in this hour. Try answering the questions before looking at the answers.

Quiz

1.

What is the relative path of the URLconf file for the following URL pattern?

(r'^Blogs/', include('mySite.Blogs.urls')),

2.

If a variable is captured in the URL pattern and also is specified in an extra options dictionary, which value is passed to the view function?

3.

If the URL Blogs/display/10 is passed into the following URL pattern, what URL is passed into the URLconf file called by the include() function?

(r'^Blogs/', include('mySite.Blogs.urls')),

Quiz Answers

1.

mySite/Blogs/urls.py

2.

The value in the dictionary

3.

display/10

Exercises

1.

Create an additional view for the People object that displays the Blog contents for a specific person.

2.

Create an URL pattern in the URLconf file that collects the person’s ID from the URL request and passes it to the view function you created in Exercise 1.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.111.49