tags:

views:

92

answers:

1

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.)

+4  A: 

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:

def custom_view(request, year, foo):
    context = RequestContext(request, {'foo': year})
    return render_to_response('my_template.tmpl', context)

The reason that you get a NameError in the case you're describing is because Python is looking for an identifier called year in the surrounding scope and it doesn't exist there -- it's only a substring in the regex pattern.

cdleary
+1: That's what view functions are for -- mapping appropriate pieces of the request to something that will be rendered in the template.
S.Lott
As a short-cut for passing all of the variables, you can also use `locals()`: `context = RequestContext(request, locals())` This is pretty dangerous as every local variable gets passed, but it can make a good shortcut.
Jack M.
I'm not a huge fan of "slow and dangerous". ;-)
cdleary