[Django]-Default parameters to actions with Django

9👍

The problem is that when the pattern is matched against ‘test/’ the groupdict captured by the regex contains the mapping ‘name’ => None:

>>> url.match("test/").groupdict()
{'name': None}

This means that when the view is invoked, using something I expect that is similar to below:

view(request, *groups, **groupdict)

which is equivalent to:

view(request, name = None)

for ‘test/’, meaning that name is assigned None rather than not assigned.

This leaves you with two options. You can:

  1. Explicitly check for None in the view code which is kind of hackish.
  2. Rewrite the url dispatch rule to make the name capture non-optional and introduce a second rule to capture when no name is provided.

For example:

urlpatterns = patterns('',
    (r'^test/(?P<name>.+)$','myview.displayName'), # note the '+' instead of the '*'
    (r'^test/$','myview.displayName'),
)

When taking the second approach, you can simply call the method without the capture pattern, and let python handle the default parameter or you can call a different view which delegates.

0👍

I thought you could def displayName(request, name=defaultObj); that’s what I’ve done in the past, at least. What were you setting the default value to?

👤mipadi

Leave a comment