[Django]-Django: Arbitrary number of unnamed urls.py parameters

15πŸ‘

βœ…

A possibility that you might consider is matching the entire string of possible values within the url pattern portion and pull out the specific pieces within your view. As an example:

urlpatterns = patterns('',
    url(r'^browse/(?P<match>.+)/$', 'app.views.view', name='model_browse'),
)

def view(request, match):
    pieces = match.split('/')
    # even indexed pieces are the names, odd are values
    ...

No promises about the regexp I used, but I think you understand what I mean.

(Edited to try and fix the regexp.)

πŸ‘€Adam

3πŸ‘

I agree with Adam, but I think the pattern in urls.py should be:

... r'^browse/(?P<match>.+)/$' ...

The β€˜\w’ will only match β€˜word’ characters, but the β€˜.’ will match anything.

πŸ‘€Peter Rowell

1πŸ‘

I’ve an alternative solution, which isn’t quite different from the previous but it’s more refined:

url(r'^my_app/(((list\/)((\w{1,})\/(\w{1,})\/(\w{1,3})\/){1,10})+)$'

I’ve used unnamed url parameters and a repetitive regexp. Not to get the β€œis not a valid regular expression: multiple repeat” i place a word at the beginning of the list.

I’m still working at the view receiving the list. But i think ill’ go through the args or kwargs.. Cannot still say it exactly.

My 2 cents

πŸ‘€softwareplay

0πŸ‘

Same answer came to me while reading the question.

I believe model_browse view is the best way to sort the query parameters and use it as a generic router.

0πŸ‘

I think the answer of Adam is more generic than my solution, but if you like to use a fixed number of arguments in the url, you could also do something like this:

The following example shows how to get all sales of a day for a location by entering the name of the store and the year, month and day.

urls.py:

urlpatterns = patterns('',
    url(r'^baseurl/location/(?P<store>.+)/sales/(?P<year>[0-9][0-9][0-9][0-9])-(?P<month>[0-9][0-9])-(?P<day>[0-9][0-9])/$', views.DailySalesAtLocationListAPIView.as_view(), name='daily-sales-at-location'),
)

Alternativly, you could also use the id of the store by changing (?P<store>.+) to (?P<store>[0-9]+). Note that location and sales are no keywords, they just improve readability of the url.

views.py

class DailySalesAtLocationListAPIView(generics.ListAPIView):
    def get(self, request, store, year, month, day):
        # here you can start using the values from the url
        print store
        print year
        print month
        print date

        # now start filtering your model

Hope it helps anybody!

Best regards,

Michael

πŸ‘€Michael

Leave a comment