Search code examples
pythondjangopython-3.xurl-pattern

Django urlpattern with infinite number of parameters


Is it possible to define Django urlpattern, which would get any number of same type parameters and pass them to a view?

Lets say I want to create a page which gets a list of numbers from url and sums them. So these would be valid urls:

/sum/10/99/12/
/sum/1/2/3/4/5/6/7/8/9/
/sum/3/

I guess that view could look like this:

def sum_view(request, *args):
    return render(request, 'sum.html', {'result': sum(args)})

Question is how should urlpattern look like? Maybe something like this:

url(r'^sum/((\d+)/)+$', views.sum_view)

But this way view gets only last number repeated twice: args == ('1/', '1'). What is the correct regular expression to get all the numbers passed ot the view?


Solution

  • You could capture a single argument, e.g. '1/2/3/4/5/6/7/8/9/'

    url(r'^sum/(?P<numbers>[\d/]+)$', views.sum_view)
    

    The split the list in the view.

    def sum_view(request, numbers):
        processed_numbers = [int(x) for x in number.split('/') if x]
        ...