Default parameters to actions with Django
-
04-07-2019 - |
Question
Is there a way to have a default parameter passed to a action in the case where the regex didnt match anything using django?
urlpatterns = patterns('',(r'^test/(?P<name>.*)?$','myview.displayName'))
#myview.py
def displayName(request,name):
# write name to response or something
I have tried setting the third parameter in the urlpatterns to a dictionary containing ' and giving the name parameter a default value on the method, none of which worked. the name parameter always seems to be None. I really dont want to code a check for None if i could set a default value.
Clarification: here is an example of what i was changing it to.
def displayName(request,name='Steve'):
return HttpResponse(name)
#i also tried
urlpatterns = patterns('',
(r'^test/(?P<name>.*)?$',
'myview.displayName',
dict(name='Test')
)
)
when i point my browser at the view it displays the text 'None'
Any ideas?
Solution
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:
- Explicitly check for None in the view code which is kind of hackish.
- 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.
OTHER TIPS
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?