2

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?

niekas
  • 8,187
  • 7
  • 40
  • 58

2 Answers2

4

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]
    ...
Alasdair
  • 298,606
  • 55
  • 578
  • 516
1

Django's urlpatterns are based on python's regexps so there is no way of catching all data from repeating group. Check this question for explanation.

You will have to split and process them by yourself (like @Alasdair suggests).

Community
  • 1
  • 1
beezz
  • 2,398
  • 19
  • 15