Site icon Tutorial

Using Generic Views

All of these views are used by creating configuration dictionaries in your URLconf files and passing those dictionaries as the third member of the URLconf tuple for a given pattern.
For example, here’s a simple URLconf you could use to present a static “about” page:

from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template

urlpatterns = patterns(”,
(‘^about/$’, direct_to_template, {
‘template’: ‘about.html’
})
)

Though this might seem a bit “magical” at first glance — look, a view with no code! —, it’s actually exactly the same as the examples in earlier chapter: the direct_to_template view simply grabs information from the extra-parameters dictionary and uses that information when rendering the view. Because this generic view — and all the others — is a regular view functions like any other, we can reuse it inside our own views. As an example, let’s extend our “about” example to map URLs of the form /about/<whatever>/ to statically rendered about/<whatever>.html. We’ll do this by first modifying the URLconf to point to a view function:

from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
from mysite.books.views import about_pages

urlpatterns = patterns(”,
(‘^about/$’, direct_to_template, {
‘template’: ‘about.html’
}),
(‘^about/(w+)/$’, about_pages),
)

Next, we’ll write the about_pages view:

from django.http import Http404
from django.template import TemplateDoesNotExist
from django.views.generic.simple import direct_to_template

def about_pages(request, page):
try:
return direct_to_template(request, template=”about/%s.html” % page)
except TemplateDoesNotExist:
raise Http404()

Here we’re treating direct_to_template like any other function. Since it returns an HttpResponse, we can simply return it as-is. The only slightly tricky business here is dealing with missing templates. We don’t want a nonexistent template to cause a server error, so we catch TemplateDoesNotExist exceptions and return 404 errors instead.

Is There a Security Vulnerability Here? – Sharp-eyed readers may have noticed a possible security hole: we’re constructing the template name using interpolated content from the browser (template=”about/%s.html” % page). At first glance, this looks like a classic directory traversal vulnerability. But is it really?

Not exactly. Yes, a maliciously crafted value of page could cause directory traversal, but although page is taken from the request URL, not every value will be accepted. They key is in the URLconf: we’re using the regular expression \w+ to match the page part of the URL, and \w only accepts letters and numbers. Thus, any malicious characters (dots and slashes, here) will be rejected by the URL resolver before they reach the view itself.

Back to Tutorial

Exit mobile version