Given:
urlpatterns = \
patterns('blog.views',
(r'^blog/(?P<year>\d{4})/$', 'year_archive', {'foo': 'bar'}),
)
in a urls.py file. (Should it be ‘archive_year’ instead
of ‘year_archive’ ? – see below for ref.)
Is it possible to capture information from the URL
matching (the value of “year” in this case) for use in
the optional dictionary?. E.g.: the value of year
instead ‘bar’?
Replacing ‘bar’ with year results in: “NameError …
name ‘year’ is not defined”.
The above is just an example; I know that year is
available in the template HTML file for archive_year,
but this is not the case for archive_month. And there
could be custom information represented in the URL that
is needed in a template HTML file.
(The example is from page “URL dispatcher”, section “Passing
extra options to view functions”,
http://docs.djangoproject.com/en/dev/topics/http/urls/,
in the Django documentation.)
No, that’s not possible within the URLConf — the dispatcher has a fixed set of things it does. (It takes the group dictionary from your regex match and passes it as keyword arguments to your view function.) Within your (custom) view function, you should be able to manipulate how those values are passed into the template context.
Writing a custom view to map year to “foo” given this URLConf would be something like:
The reason that you get a
NameErrorin the case you’re describing is because Python is looking for an identifier calledyearin the surrounding scope and it doesn’t exist there — it’s only a substring in the regex pattern.