Optional number of wildcards in URL patterns in Django
-
14-04-2021 - |
Question
#views.py
def sum(*args):
return reduce((lambda x, y: int(x)+int(y)), args)
Is it possible to write one URL pattern that will handle uniformly such requests as /sum/1/2 (result = 3), /sum/1/2/3 (result = 6), etc.?
Solution
It's not exactly what you want, but you could use
(r'^sum/(?P<allargs>[/0-9]+)$', 'views.sum')
and then
def sum(request, allargs):
args = map( int, allargs.split('/') )
# Compute sum
OTHER TIPS
Unless you absolutely want to use the form "/1/2/3", you'd rather use query string "/sum?1&2&3". It will be much simpler to implement.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow